user9098366
user9098366

Reputation:

How matching the regex part before a "?" can cause an expression to fail?

"The question mark gives the regex engine two choices: try to match the part the question mark applies to, or do not try to match it. The engine always tries to match that part. Only if this causes the entire regular expression to fail, will the engine try ignoring the part the question mark applies to."

This is from here - https://www.regular-expressions.info/optional.html

How matching the part before the "?" in any example of regex code can cause the "entire regular expression to fail"?

It checks if it matches first. It matches, ok - it will go with that. It does not match, ok it will go with that. But the fact that it matches can cause the entire expression to fail? Is there a way of coming up with an example of a situation like that?

Upvotes: 0

Views: 24

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

Consider a simple regex

A?A

which matches strings A and AA.

When you pass AA to this regex, A? matches the first A, and the second A matches the last A.

When you pass a single A to it, A? again matches A, but then the final A has nothing to match

Regex engine sees that keeping the match of A? would cause the regex to fail, and tries again with A? not matching anything. This time, A remains available for the final A to match, so the expression succeeds after "backtracking."

Upvotes: 1

Related Questions