Reputation: 268
Okay, so I have this small regex program in python
#!/usr/bin/python
import re
string = "val1=1 val2=2 val3=234"
valfinder = re.compile('val\d=(?P<values>\d)')
vals = valfinder.search(string)
print(vals.group('values'))
it prints out 1.
What is a way for it to match to all the other values?
How would I access them?
Upvotes: 0
Views: 161
Reputation: 208485
Use either findall()
to get a list of the matches as strings, or finditer()
to get an iterator over the match objects, for example:
>>> valfinder.findall(string)
['1', '2', '2']
>>> for match in valfinder.finditer(string):
... print match.group('values')
...
1
2
2
Note that the behavior of findall()
changes depending on how many capturing groups there are in your regex. If there are no capturing groups each element in the result with be the entire match, if there is one capturing group each element will be whatever that group matched, and if there is more than one group each element will be a tuple of the group matches.
Upvotes: 1