Ari Seyhun
Ari Seyhun

Reputation: 12531

Regex OR pipe not working as expected

I'm attempting to match multiple regular expressions in a single regular expression.

Given two extremely complex regular expressions, how could I keep them separate, yet put them into a single expression which matches both. I thought that was the use of the regex OR pipe, but it seems to not be working as I expected.

As a basic example, I'm working with the following regular expression:

(?:\s*(\w+)\s*:)|(?:\:\s*(\w+)\s*\,)

Testing with the following string:

{key: value, name: "John", age: 17}

And expecting it to capture in the two (\w+) capture groups:

key, value, name and age

But it is only capturing key, name and age without the value.

I can confirm the 2nd part of my expression (after the OR pipe) does indeed match the value when the first part of the expression is omitted (before the OR pipe).


Can someone please explain and provide a solution as to why it is not matching both key and value and only matching key.

Upvotes: 1

Views: 968

Answers (2)

Armali
Armali

Reputation: 19375

In my expression, something causes the OR pipe to not work :/

Can someone please explain …

Actually, with "you are capturing : in both groups so the | can't match both" KinSlayerUY did explain why, in your view, something causes the OR pipe to not work. In other words: Since the alternative to the left of | already contained the : after key, there was no : available to match the alternative to the right with : value, (remember that matches don't overlap).

Upvotes: 1

KinSlayerUY
KinSlayerUY

Reputation: 1940

Seems that you are capturing : in both groups so the | can't match both

This should work

(?:\s*(\w+)\s*:)|(?:\s*(\w+)\s*\,)

Regex101 live example

Upvotes: 2

Related Questions