开发者

Regex optional group fails whole search [closed]

开发者 https://www.devze.com 2023-04-01 10:33 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help 开发者
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help 开发者_如何学Cclarifying this question so that it can be reopened, visit the help center. Closed 9 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消