Search code examples
javaregexstringquantifiers

Regular Expression: Backtracking in Possessive Quantifier


I was reviewing a test and noticed that a possessive quantifier actually worked in an str.split(). so I wrote the following code:

String str = "aaaaab";

if(str.matches("a*+b"))
    System.out.println("I backtrack");
else
    System.out.println("Nope.");

When run, this prints out I backtrack. Here's why this is confusing, I've been told that a possessive quantifier never backtracks, so why would a*+ give up the b in the String?

What I want is a more detailed explanation of when possessive quantifiers backtrack.


Solution

  • There is no backtracking in your example.

    You are saying "any number of a characters". So, the engine will collect those 5 a chars and then stop; to then find the b.

    That is all there is to this.

    Backtracking means that the engine has to "track back" after collecting too much of the input string; see here for an example of that.

    And beyond that: your if condition returns true when the pattern matches the input. Your conclusion that this means "it is backtracking" is not correct:

    A match is a match; no matter if the engine had to backtrack in order to match (or not). In other words: your little test there doesn't tell you anything (it only tells you if the input matched the given pattern; period).