Search code examples
.netregexnon-greedy

Non-greedy regex quantifier gives greedy result


I have a .net regex which I am testing using Windows Powershell. The output is as follows:

> [System.Text.RegularExpressions.Regex]::Match("aaa aaa bbb", "aaa.*?bbb")


Groups   : {aaa aaa bbb}
Success  : True
Captures : {aaa aaa bbb}
Index    : 0
Length   : 11
Value    : aaa aaa bbb

My expectation was that using the ? quantifier would cause the match to be aaa bbb, as the second group of a's is sufficient to satisfy the expression. Is my understanding of non-greedy quantifiers flawed, or am I testing incorrectly?

Note: this is plainly not the same problem as Regular Expression nongreedy is greedy


Solution

  • This is a common misunderstanding. Lazy quantifiers do not guarantee the shortest possible match. They only make sure that the current quantifier, from the current position, does not match more characters than needed for an overall match.

    If you truly want to ensure the shortest possible match, you need to make that explicit. In this case, this means that instead of .*?, you want a subregex that matches anything that is neither aaa nor bbb. The resulting regex will therefore be

    aaa(?:(?!aaa|bbb).)*bbb