Wednesday, 15 June 2011

Can I use multiple search criteria in one python regex query to return a tuple? -



Can I use multiple search criteria in one python regex query to return a tuple? -

i have log file appends new logs programme runs on different days. each iteration there new product version , launch switch. need product version: [0-9-]*and launch switch: \w* each iteration tuple.

currently doing this:

ver = re.findall(r'(?<=product version: )[0-9.]*', s) launch = re.findall(r'(?<=launch switch: )\w*', s)

then later i'm iterating through ver , launch create tuples. works, it's not pretty , i'm sure there's more pythonic way of doing this.

you can utilize multiple capturing groups within regex pattern; re.findall homecoming them tuple. example:

>>> info = "product version: 0.0.1 | launch switch: hello | product version: 2.3.4 | launch switch: world" >>> re.findall("product version: ([0-9.]+).*?launch switch: (\w+)", data) [('0.0.1', 'hello'), ('2.3.4', 'world')]

from the re.findall docs:

return non-overlapping matches of pattern in string, list of strings. string scanned left-to-right, , matches returned in order found. if 1 or more groups nowadays in pattern, homecoming list of groups; this list of tuples if pattern has more 1 group. empty matches included in result unless touch origin of match.

python regex tuples

No comments:

Post a Comment