0

Given a string such as aaa|bbb, is it possible to use RegExp (let's say PCRE) to check if the number of as before the pipe is the same as the number of bs after it? So, in this string:

aaa|bbb
a|b
|
aaaaa|bbbbb

should all be matched, while

aaa|b
aaa|bb
aaa|bbbb
|b
a|
aa|b

should not be matched.

Is there any way to achieve this using only RegExp? I've tried using lookarounds to match the pipe character only if the lookaround conditions are met, by doing something like:

aaa|bbb
  ^ ^
  test

aaa|bbb
 ^   ^
  test

aaa|bbb
^     ^

but I couldn't figure any way of going over the same area twice, due to the linearity of RegExp. It would be possible to implement using nested lookarounds, but then the number of nests would have to be hard-coded, which would mean it wouldn't work with any number of elements, only up to the amount of lookarounds that one nests by hand.

Geza Kerecsenyi
  • 1,127
  • 10
  • 27
  • It is not possible. Answering why will take much longer, but the main points are 1) no recursion, 2) no forward references, 3) no possessive quantifiers/atomic groups support. – Wiktor Stribiżew Feb 04 '20 at 22:03
  • yeah, without recursion in javascript regex... The only way seems to be an akward dumb way. I.e. checking for each `a{n}-b{n}` length. `/^(a\|b|aa\|bb|aaa\|bbb)$/` . Well, perhaps regex recursion could be possible via a library like [xregexp](http://xregexp.com/), but I never tried that. – LukStorms Feb 04 '20 at 22:53
  • @WiktorStribiżew I've updated my question now to allow for PCRE RegExp instead of JS. The actual language doesn't matter to me. – Geza Kerecsenyi Feb 05 '20 at 07:17
  • Then it is a duplicate, see [this answer](https://stackoverflow.com/a/3650562/3832970). – Wiktor Stribiżew Feb 05 '20 at 07:54
  • It can't be done, because RegExp hasn't a way to count, but, you always can manipulate it as I do here: https://regex101.com/r/haoxT8/1 which works – Almog Feb 05 '20 at 10:21
  • PCRE? Try this : `\b(?=a+\|b+\b)(a(\|?(?1)?)b)\b` It uses a recursive. The positive lookahead is there to assure 1 pipe. [test](https://regex101.com/r/Qzae6I/1) – LukStorms Feb 05 '20 at 14:33

0 Answers0