Interesting question! “Backtracking” might happen only when you use a quantifier. For example, when you try to match
+ quantifier is greedy, and it will prefer to consume as many characters as it can. So, at the beginning,
[abcd]+ will eat up the whole string first, but then,
ddd does not match, so
[abcd]+ must drop at least one character. This is called backtracking. First it goes back to
a, when the whole regex finally matches.
There are modifiers to make the quantifiers non-greedy, namely the
? modifier. For example, matching
[abcd]+? part will prefer to consume as few characters as it can, so only
a is used at the beginning. Regex
ddd matches string
ddd, so no backtracking will happen.
+ can completely disable backtracking, and in this case, when the remaining part does not match, the regex simply fails. For example, matching
.++ will consume as many characters as it can, and in this case, the whole string. But the remaining string (empty string) does not match
@foo\.bar, so the regex will just not match. For another example, try matching
[^@]++ will consume as much as it can, and in this case,
@foo\.bar matches string
@foo.bar, so the regex succeeds to match.
Oracle’s document on Regexes: