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 \.
加载中,请稍侯......
精彩评论