Newbie RE question

Tim Chase python.list at tim.thechases.com
Fri Sep 22 15:46:22 EDT 2006


> I would like to search for any of the strings in r'/\:*?"<>|' in a
> string using RE module.  Can someone tell me how?

use the search() method of the regexp object.

r = re.compile(r'[/\:*?"<>|]')
results = r.search(a_string)

or, if you're interested in the first location:

r.finditer(target).next().start()

Or you can do it without the RE module:

s = set(r'/\:*?"<>|')
results = ''.join(c for c in a_string if c in s)

or, if you're interested in the indexes

index = ([i for i,c in enumerate(a_string) if c in s] or [-1])[0]

which could also be done as

index = -1
for i,c in enumerate(a_string):
	if c in s:
		index = i
		break



YMMV,

-tkc










More information about the Python-list mailing list