开发者

How do you match something surrounded by 'foo' and 'bar' without matching foo and bar?

开发者 https://www.devze.com 2022-12-20 21:00 出处:网络
as opp开发者_如何学Pythonosed to regex:\'foo.+bar\'Use a group: foo(.+?)bar Then you will be able to refer to the group as $1 or \\1, depending on the language and what you are doing with it.

as opp开发者_如何学Pythonosed to regex:'foo.+bar'


Use a group:

foo(.+?)bar

Then you will be able to refer to the group as $1 or \1, depending on the language and what you are doing with it.

As always, let me recommend Regular-Expressions.info for learning all about regexes.


An alternative would be to use lookaround if the regex flavor you're using (which you didn't specify) supports it. .NET, Python do, Ruby and JavaScript don't (fully), for example:

(?<=foo).+(?=bar)

matches any number of characters if they are preceded by foo and followed by bar.


Just use:

/foo(.+)bar/


You can use:

foo(.+?)bar

or

foo(.*?)bar

The 2nd one will work even when there is nothing between foo and bar

0

精彩评论

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

关注公众号