Pattern: a(?(?<! ) )b (c)
Input: a b c
Desription: Condition should match space, if lookbehind is not a space.
It matches correct, but the capture group $1 is empty (instad of containing c).
Is this a problem with .net regex or am I missing something?
Example: http://regexstorm.net/tester?p=a(%3f(%3f%3C!+)+)b+(c)&i=a+b+c
I'm not sure if this behavior is documented or not (if yes then I didn't find it) but using a conditional construct including an explicit zero-width assertion as its expression (?(?=expression)yes|no)
overrides the very next numbered capturing group (empties it). You can confirm this by running below RegEx:
a(?(?<! ) )b (c)()
Four ways to overcome this issue:
Enclosing expression in parentheses noted by @DmitryEgorov (that also keeps second capturing group intact) and is not included in result - the right way:
a(?((?<! )) )b (c)
As this behavior is only applied to unnamed capturing groups (default) you can get expected result using a named capturing group:
a(?(?<! ) )b (?<first>c)
Adding an extra capturing group where ever you like between (c)
and conditional:
a(?(?<! ) )(b) (c)
Avoiding such an expression if possible. E.g:
a(?( ) )b (c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With