Trouble with regex

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Fri Nov 14 10:03:28 EST 2003


Fernando Rodriguez wrote:
> Hi,
> 
> I'm trying to write a regex that finds whatever is between ${  and } in a text
> file.
> 
> I tried the following, but it only finds the first occurrence of the pattern:
> 
> 
>>>>s = """asssdf${123}
> 
> dgww${one}    ${two}"""
> 
>>>>what = re.compile("\$\{([^}]*)\}")
>>>>m = what.search(s)
>>>>m.groups()
> 
> ('123',)
> 
> What am I doing wrong? O:-)

Nothing ;) search just finds first match. If you want to find all 
non-overlapping matches try finditer:

import re

s = """asssdf${123}

dgww${one}    ${two}"""

what = re.compile("\$\{([^}]*)\}")
for m in what.finditer(s):
     print m.groups()

prints:
('123',)
('one',)
('two',)

regards,
anton.





More information about the Python-list mailing list