.net - Non-greedy regex quantifier gives greedy result -
i have .net regex testing using windows powershell. output 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 using ?
quantifier cause match aaa bbb
, second group of a's sufficient satisfy expression. understanding of non-greedy quantifiers flawed, or testing incorrectly?
note: plainly not same problem regular expression nongreedy greedy
this common misunderstanding. lazy quantifiers not guarantee shortest possible match. make sure current quantifier, current position, not match more characters needed overall match.
if want ensure shortest possible match, need make explicit. in case, means instead of .*?
, want subregex matches neither aaa
nor bbb
. resulting regex therefore be
aaa(?:(?!aaa|bbb).)*bbb
Comments
Post a Comment