Reputation: 1135
I need to find all strings in a word that match the regex. And I need to compile it first and then print the words, this is what I done:
prog = re.compile(pattern)
result = prog.match(string)
for i in result:
print i
it raises error. What should I change ?
Upvotes: 1
Views: 75
Reputation: 15195
The method .match does not return directly the strings of the match, but a so called match object.
Something like that.
<_sre.SRE_Match object at 0x0041FC80>
What you want to do is following:
prog = re.compile(pattern)
matches = prog.findall(string)
for i in matches():
print i
Upvotes: 1
Reputation: 239553
The SRE_Match
returned by match
function is not iterable. You might have wanted to iterate over the list of all the matched items. In that case, you have to use findall
function like this
result = prog.findall(string)
For example,
import re
prog = re.compile("([a-z])")
result = prog.findall("a b c")
for i in result:
print i
Output
a
b
c
Upvotes: 3