Regex With Conditional - Not Desired Output

Viewed 59

Was actually glossing over a question and found myself struggling to perform something really simple. If a string contains % I want to use a particular regex, else I want to use a different one.

I tried the following: https://regex101.com/r/UvFZpo/1/

Regex: (%)(?(1)[^$]+|[^%]+).

Test string: abc%

But I'm not getting the expected results.

I was expecting to see abc% matched as it contains %. If the string was, abc$, I'd expect it to use the second expression.

Where am I going wrong?

1 Answers

Regex parses strings from left to right, position by position.

Once your pattern matches &, its index is at the end of string, hence, it fails since there are no more chars to be matched by the subsequent [^$]+ pattern.

You can use a mere alternation here:

^(?:([^$]*%[^$]*)|([^%]+))$

See the regex demo

If the string contains %, the Group 1 will be populated, else, Group 2 will.

Details

  • ^ - start of string
  • (?:([^$]*%[^$]*)|([^%]+)) - either of the two alternatives:
    • ([^$]*%[^$]*) - Group 1: any 0+ chars other than $, as many as possible, % any 0+ chars other than $, as many as possible,
    • | - or
    • ([^%]+) - any 1+ chars other than %, as many as possible
  • $ - end of string.
Related