I have a strings like:
0011
01
000111
000111
I need to validate them like this: count of "0" must be identical to the count of "1". So "001" - invalid, "0011" - valid.
How can I do this with regex?
I have a strings like:
0011
01
000111
000111
I need to validate them like this: count of "0" must be identical to the count of "1". So "001" - invalid, "0011" - valid.
How can I do this with regex?
In Ruby, you can use subroutines:
m = /\b(0(\g<1>)?1)\b/.match('000111');
puts m;
000111
Or, you can just use capturing groups to match adjacent 0
s and 1
s, and then check the captured group length:
m = /(0+)(1+)/.match('0011');
puts m[1].length === m[2].length ? "True" : "False";
m = /(0+)(1+)/.match('00111');
puts m[1].length === m[2].length ? "True" : "False";
You may add ^
and $
to only match a string consisting of leading zeros and trailing 1
s (m = /^(0+)(1+)$/.match('00111');
).
Output of the demo program:
True
False