Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy regex doesn't work as expected C#

I have the following regex: a?\W*?b and I have a string ,.! ,b
When searching for a match I get ,.! ,b, but not just b as I expect. Why is that? How to modify the regex to get what I need?
Thank you for your help.

like image 522
StuffHappens Avatar asked Mar 22 '26 11:03

StuffHappens


2 Answers

A lazy quantifier doesn't help here for what you want. Let's see what's happening.

The regex engine starts at the beginning of the string. First tries to match a. It can't, but it's no problem since the a is optional.

Then, there is a lazy \W*? so the regex engine skips it but remembers the current position.

It then tries to match b. It can't, so it backtracks and successfully matches the , with \W*?. It then goes on to try and match b (because of the lazy quantifier). It still can't and backtracks again. This repeats a few times until finally the regex engine has arrived at the b. Now the match is complete - the regex engine declares success.

So the regex works as specified - just not as intended. Now the question is: What exactly do you want the regex to do?

For example, if what you really want is:

Match b alone, unless it's preceded by a and some non-word characters, in which case match everything from a to b, then use

b|a\W*b
like image 79
Tim Pietzcker Avatar answered Mar 25 '26 01:03

Tim Pietzcker


A lazy expression is only lazy from the right, i.e. it will be as short as possible by removing characters on the right, but it will not remove characters on the left.

To make the match start later, you need a greedy expression before it that swallows the characters that you don't want to match.

Alternatively, as Tim showed, you can make the match start later by only matching the first character and the following separators if the first character exists.

like image 25
Guffa Avatar answered Mar 25 '26 01:03

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!