Re.match () several times on the same line as Python

I have a regex to find: ABC: `hello` pattern. This is the code.

format =r".*\:(.*)\:\`(.*)\`"
patt = re.compile(format, re.I|re.U)
m = patt.match(l.rstrip())
if m:
    ...

This works well when a pattern occurs once per line, but with the example ": tagbox:` Verilog`: tagbox: `Multiply`: tagbox:` VHDL`. It only finds the last one.

How can I find all three patterns?

EDIT

Based on Paul Z's answer, I could make it work with this code

format = r"\:([^:]*)\:\`([^`]*)\`"
patt = re.compile(format, re.I|re.U)
for m in patt.finditer(l.rstrip()):
    tag, value = m.groups()  
    print tag, ":::", value

Result

tagbox ::: Verilog
tagbox ::: Multiply
tagbox ::: VHDL
+3
source share
2 answers

Yes, dcrosta suggested looking at the docs re, which is probably a good idea, but I'm sure you really need a function finditer. Try the following:

format = r"\:(.*)\:\`(.*)\`"
patt = re.compile(format, re.I|re.U)
for m in patt.finditer(l.rstrip()):
    tag, value = m.groups()
    ....

, .* , , (). , , , , , .* , , , " , ". finditer .

+7

re docs? re.match ( ), re.findall ( ), match search RegexObject s, , . . split, , . , , .

+2

All Articles