0

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Nikita
  • 9
  • 2

1 Answers1

0

In Ruby, you can use subroutines:

m = /\b(0(\g<1>)?1)\b/.match('000111');
puts m;

Result of the demo:

000111

Or, you can just use capturing groups to match adjacent 0s and 1s, 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 1s (m = /^(0+)(1+)$/.match('00111');).

Output of the demo program:

True
False
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • It can be done if you adapt `'/ ^ (a (?1)? b) $ /x'` to Ruby: http://rubular.com/r/9JZfVgVosj – nhahtdh May 13 '15 at 12:10
  • I have found out where I was wrong thanks to [rexegg.com](http://www.rexegg.com/regex-disambiguation.html) I was just unaware of the `\g<1>` notation. Your suggestion - `^(?a\g?b)$` - is also working well, as I see. – Wiktor Stribiżew May 13 '15 at 12:15
  • Oh, `\g<1>` works. Rubular's error message is really misleading. – nhahtdh May 13 '15 at 12:17