开发者

How to use the pipe operator as part of a regular expression? [duplicate]

This question already has answers here: What is a non-capturing group in regular expressions? (18 answers) Closed 4 months ago.

I want to match the url within strings like

u1 = "Check this out http://www.cnn.com/stuff lol"
u2 = "see http://www.cnn.com/stuff2"
u3 = "http://www.espn.com/stuff3 is interesting"

Something like the foll开发者_StackOverflow社区owing works, but it's cumbersome because I have to repeat the whole pattern

re.findall("[^ ]*.cnn.[^ ]*|[^ ]*.espn.[^ ]*", u1)

Particularly, in my real code I wanted to match a much larger number of web sites. Ideally I can do something similar to

re.findall("[^ ]*.cnn|espn.[^ ]*", u1)

but of course it doesn't work now because I am not specifying the web site name correctly. How can this be done better? Thanks.


Non-capturing groups allow you to group characters without having that group also be returned as a match.

cnn|espn becomes (?:cnn|espn):

re.findall("[^ ]*\.(?:cnn|espn)\.[^ ]*", u1)

Also note that . is a regex special character (it will match any character except newline). To match the . character itself, you must escape it with \.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜