javaregexregex-lookarounds

Confusing behavior of a capturing group in a positive lookbehind in a Java regex with Pattern.matcher


The following issue is observed only on Java and not on other regex flavors (e.g PCRE).

I have the following regex: (?:(?<=([A-Za-z\d]))|\b)(MyString). There's a capturing group on [A-Za-z\d] in the lookbehind.

And I'm trying to match (through Pattern.matcher(regex); to be precise, I'm calling replaceAll) the following string: string.MyString.

On PCRE, I will match MyString, and it will be the second group in the match. On Java, however, I will match the g in string as group 1, and MyString as group 2.

  1. Why does Java do that? To me this regex implies that a character matching [A-Za-z\d] should only be matched if it directly precedes MyString, which is not the case here.
  2. How can I avoid that and not match this g? I want to keep the capturing group in case I have to match a string like stringMyString, in which case I do need that g as group 1.

Solution

  • There is a line on the java.util.regex.Pattern docs

    The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.

    I think this line explains the behavior:

    The last line:

    So if you have this string:

    string.MyString.srting.MyString
    

    And this regex:

    (?:(?<=([tr]))|\b)(MyString)
    

    You can see that the group 1 value is different in both matches as all captured input is discarded.

    See an example on regex101