Trouble with regex

F

Fernando Rodriguez

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:)
 
A

anton muhin

Fernando said:
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:


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.
 
J

Jim Shapiro

Fernando Rodriguez said:
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:)

Try:

import re

s = """asssdf${123}
dgww${one} ${two}"""
what = re.compile("\$\{([^}]*)\}") # same as original
m = what.findall(s)
print m
regex_test.py
['123', 'one', 'two']

HTH

Jim Shapiro
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top