[Tutor] String searching

Craig Hagerman craig@osa.att.ne.jp
Wed, 31 May 2000 20:53:18 +0900


Hi Andr,

鯖 always think of regular expressions first for this kind of problem
instead of string methods. How about something like:

import re
isHyperlink = re.compile('(http|ftp)://["¥'](.*?) ["¥']',re.IGNORECASE)

for word in text.readlines():
	if isHyperlink.search(word):
		do stuff with word

You can use this regex to find a hyperlink AND extract the URL:
isHyperlink.search(word).group(2)

I haven't used re.findall() before but I *think* that you can also do this:

import re
for isHyperlink.findall(text):
	do stuff with word


>Hi everyone,
>
>I'm trying to find out if a certain word in a string is a hyperlink, in
>other words if it starts with http:// or ftp://. I've come up with a
>way that works, but I think there must be some less uglier way of doing
>this. Here's the solution I use now:
>
>for word in string.split(text):
>	if "http://" == word[0:7] or "ftp://" == word[0:6]
>		do stuff with word...
>
>The test itself is what I think is ugly, and I would have prefered to
>use something like:
>
>if "http://" or "ftp://" in string.split(text):
>	get the whole word that matched...
>
>But I don't know how to get this whole match. I would be greatful for
>any advice.