简体   繁体   中英

Python regex groups with multiple possible values

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM