Search code examples
regexregex-lookaroundsregex-groupregex-greedy

RegEx for matching repeating [01] using capturing groups


I have a variable-length string of values (bits actually: 1 and 0, multiples of 32). Eg:

010011011001110111100111011010001001100011101100100011100010100011110010100011001111111101101001

Each of the 32 bit blocks contains an inner structure: first 8 bits and next 24 bits belong togehter.

I like to

  • Fetch each 32 bit block and
  • each block's inner structure

in one regex.

My approach

^(([01]{8})([01]{24})){0,}$

didn't work out since it only matches the last block.

Is such a regex possible? What to look for? What an I doing wrong?


Solution

  • I have slightly modified it using this tool:

    (([0-1]{8})([0-1]{24}))
    

    If I understand correctly, you may not want to bound it with start and end chars. You can simply use another capturing group around it and with the other two capturing groups that you already have, extract the data, as you wish.

    u

    RegEx Descriptive Graph

    This link helps you to visualizes your expressions:

    enter image description here

    JavaScript Testing Demo

    const regex = /(([0-1]{8})([0-1]{24}))/gm;
    const str = `010011011001110111100111011010001001100011101100100011100010100011110010100011001111111101101001
    `;
    const subst = `Group #1: $1\nGroup #2: $2\nGroup #3: $3\n`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);

    Performance Test

    This snippet returns the runtime of a 1-million times for loop.

    const repeat = 1000000;
    const start = Date.now();
    
    for (var i = repeat; i >= 0; i--) {
    	const regex = /(([0-1]{8})([0-1]{24}))/gm;
    	const str = `010011011001110111100111011010001001100011101100100011100010100011110010100011001111111101101001`;
    	const subst = `\nGroup #1: $1\nGroup #2: $2\nGroup #3: $3`;
    
    	var match = str.replace(regex, subst);
    }
    
    const end = Date.now() - start;
    console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
    console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");