Is there any difference between these two regular expression patterns (assuming single-line mode is enabled): a.*?b
and a[^b]*b
? What about in terms of performance?
a.*?b
has to check at each consumed character if it matches the pattern (i.e. if the next one is a b
). This is called backtracking.
With the string a12b
the execution would look like this:
a
b
? No.a1
). Is the next one a b
? No.a12
). Is the next one a b
? Yes!b
a[^b]*b
consumes anything that isn't a b
without asking itself questions and is much faster for longer strings because of that.
With the string a12b
the execution would look like this:
a
b
. (a12
)b
RegexHero has a benchmark feature that will demonstrate that with the .NET regex engine.
Other than the performance difference, they match the same strings in your example.
However there are situations where there is a difference between the two. In the string aa111b111b
(?<=aa.*?)b
matches both b
while (?<=aa[^b]*)b
matches only the first one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With