Reputation: 150
In python there is a syntax for - if a capture group exists then x else y e.g.
>>> pat = re.compile('(?:(a)|(c))b(?(1)a|c)') # should only match 'aba' or 'cbc'
>>> pat.match('abc')
None
>>> pat.match('aba')
<re.Match object; span=(0, 3), match='aba'>
>>> pat.match('cba')
None
>>> pat.match('cbc')
<re.Match object; span=(0, 3), match='cbc'>
How might one achieve a similar expression in javascript.
Leading to a general approach for converting the python regex syntax to javascript
(?(id/name)yes-pattern|no-pattern)
I've tried a few ideas but haven't found an approach that's worked
Upvotes: 1
Views: 513
Reputation: 43206
I'm not sure if Javascript has conditionals the way python does, but I think something like this should work:
/(.+(?<=^(a|c))b(a|c))$/g
The .+
at the front is used to actually accumulate tokens, and then the conditional is replaced with a positive look-behind (?<=...
) but instead of a reference, we include the actual pattern we are looking for.
Upvotes: 0
Reputation: 371019
For this particular case, you don't need if/else syntax, you can backreference a single capture group:
const pattern = /([ac])b\1/;
console.log(
pattern.test('abc'),
pattern.test('aba'),
pattern.test('cbc'),
);
Upvotes: 1