Search code examples
regexregex-group

Regex quantifier more than one group


I need a regex to get a sequence of number 1 followed by number 0 and the total numbers should be equal to a max length. Is there a way to do something like (([1]+)([0]+)){maxLength} ?

Ex.: maxLength = 7

10 -> should not pass (total length < maxLength)
1111100 -> should match
1000000 -> should match
11110000000 -> should match 1111000.
111111111111 -> should match 1111111.

Plus: The sequence could be 0 followed by 1, and the greater the amount of 1 the better (I don't know if it's possible in only one regex). 000000001111 -> should get 0001111.

I'm focusing on 1 followed by 0.

I started with [1]+[0]+, after I quantified the 0s ([1]+)([0]{1,7}), but it still giving more 0s than I want.

Then I was thinking in ([1]{7,}|[1]{6}[0]{1}|[1]{5}[0]{2}|[1]{4}[0]{3}|[1]{3}[0]{4}|[1]{2}[0]{5}|[1]{1}[0]{6}), and ok, it works. BUT if maxLength = 100 the above solution is not viable.

Is there some way to count the length of the first matched group and then the second group to be the difference from the first one?

Or something like (([1]+)([0]+)){7} ?


Solution

  • It seems you just want:

    ^(?:(?=1+0*$)|(?=0+1*$))[01]{7}
    

    Here the {7} can be replaced with whatever the max length is minus one.