.net regex with condition lookbehind and capture group

前端 未结 2 2087
别那么骄傲
别那么骄傲 2020-12-19 09:22

Pattern: a(?(?

Input: a b c

Desription: Condition should match space, if lookbehind is not a space.

It ma

2条回答
  •  Happy的楠姐
    2020-12-19 10:08

    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(?(?

    Four ways to overcome this issue:

    1. Enclosing expression in parentheses noted by @DmitryEgorov (that also keeps second capturing group intact) and is not included in result - the right way:

      a(?((?
    2. As this behavior is only applied to unnamed capturing groups (default) you can get expected result using a named capturing group:

      a(?(?c)
      
    3. Adding an extra capturing group where ever you like between (c) and conditional:

      a(?(?
    4. Avoiding such an expression if possible. E.g:

      a(?( ) )b (c)
      

提交回复
热议问题