repeating regular expressions in one string

Carl J. Van Arsdall cvanarsdall at mvista.com
Wed Nov 16 15:18:29 EST 2005


Shane wrote:
> Hi folks,
>
> I'm new to regular expressions (and a novice at Python) but it seems to be the tool I need for a particular problem. I have a bunch of strings that looks like this:
>
> 'blahblah_sf1234-sf1238_blahblah'
>
> and I would like to use the re module to parse all the 'sfXXXX' parts of the string. Each 'sfXXXX' needs to be its own string when I am through. How do I compile a regular expression that looks for more than one instance? Currently my expression looks like this:
>
> myString = re.compile('sf[0-9][0-9][0-9][0-9]')
>
>   
Well, since all your strings come in the same format you might try 
something like

myString = re.compile(r'\w+_(sf\d\d\d\d)-(sf\d\d\d\d)_\w+')

then when you do your matching:

extracted = myString.match(originalStrnig)

your two extracted strings would be accessible via:

extracted.group(1)
extracted.group(2)


> This works great for finding the first instance of 'sfXXXX'. I hope that was clear :)
>
> Thanks,
>
> Shane
>   



More information about the Python-list mailing list