Newbie RE question

Tim Chase python.list at tim.thechases.com
Mon Sep 25 14:49:54 EDT 2006


1) Please don't top-post...it makes it hard to reply in context

2) You may want to "reply to all" so that the mailing list gets 
CC'd...there are lots of smart folks on the list, and by replying 
only to me, you limit your options to the meager extents of my 
knowledge.

>>> 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)
>>
> Thank you very much for your helpful reply.  Could you tell me what I can do
> once I do:
> 
> r = re.compile(r'[/\:*?"<>|]')
> results = r.search(a_string)
> 
> I'm not sure what I can do with the result variable?

Well, your original post only asked /how/ to search for one of 
those characters ("Can someone tell me how?"), but failed to 
specify /what/ you wanted to do with the results.

If you wanted the index of the first one, then

	results.start()

will return that.

If you want the character in that set that was found first, it is 
found in

	results.group(0)

Or, if you want them all, you can use

	r.findall(a_string)

which will return a list of all the characters in that set that 
were found in a_string.

Using the interpreter's built-in help and introspection can be 
immensely helpful, as you can do things like

 >>> dir(results) # to find what you can do with the results
 >>> dir(r)# find out what a compiled regex object can do
 >>> help(results.start) # learn about the start() function

Just a few pointers,

-tkc








More information about the Python-list mailing list