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.
I have the following regex: a?\W*?b and I have a string ,.! ,b When
Share
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 theais 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 matchb(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 theb. 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
balone, unless it’s preceded byaand some non-word characters, in which case match everything fromatob, then use