6

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 following 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.

ceiling cat
  • 5,501
  • 9
  • 38
  • 51
  • 1
    note that with the current pattern you have, this produces a match: `re.findall("[^ ]*.cnn.[^ ]*|[^ ]*.espn.[^ ]*", 'abc.espnw.abc')` because dot matches all characters. You need to escape the dot: `re.findall("[^ ]*\.cnn\.[^ ]*|[^ ]*\.espn\.[^ ]*", 'abc.espnw.abc')` – Lie Ryan Apr 24 '11 at 22:04
  • thanks, sometimes I am not very careful... – ceiling cat Apr 24 '11 at 22:12

1 Answers1

8

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 \.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 2
    I call those “non-grouping parentheses”; the word “matches” is just confusing given that REs use that in a different sense too. – Donal Fellows Apr 24 '11 at 22:02
  • All instances of `.` in your answer should be escaped, otherwise it will match anything that has `espn` or `cnn` in it, such as `Last night on cnn there was`, which is not a desired match. – Matt Aug 30 '12 at 13:28