Regex optional group fails whole search [closed]
I'm stuck with something obvious which I can't make working:
There is a text like: ".... blah-blah-blah... Grupper blah-blah-blah Butik ...
".
Grupper
is an optional token - can be omitted in text and Butik - is mandatory. So it should match Grupper
if there is one and Butik
always.
Expression like (Grupper)?[\s\S]*?(Butik)
never catches Grupper
, but without ? works fine (and fails completely, of course, when there are no 'Grupper' in original text).
How do I get it to work?
(Grupper)?
matches Grupper if it appears 0 or 1 times. So it matches something, even if Grupper isn't part of it.
If your string starts with Grupper, the backreference (Grupper)
will contain it (Regular Expressions are greedy by default), and if the string doesn't start with Grupper, the backreference will be empty.
In your place, I would catch Butik and Grupper in 2 different regular expressions.
精彩评论