for循环中的正则表达式
在Python中,怎么把正则表达式和for循环一起用呢?
example data
abc 1 xyz 0
abc 2 xyz 1
abc 3 xyz 2
那怎么写一个正则表达式来匹配下面这样的内容呢?
for i in range(1, 3):
re.match(abc +i xyz +(i-1))
2 个回答
2
你不能用一个正则表达式来包含在匹配时计算的数学表达式。不过,你可以动态生成正则表达式,使用常见的Python字符串格式化技巧:
import re
example_data = """
this line will not match
abc 1 xyz 0
this line will not match
abc 2 xyz 1
abc 2 xyz 2 will not match
abc 3 xyz 2
"""
for i in range(1, 4):
pattern = "abc %d xyz %d" % (i, (i - 1))
match_group = re.search(pattern, example_data)
if match_group:
print match_group.group(0)
这段代码会输出:
abc 1 xyz 0
abc 2 xyz 1
abc 3 xyz 2
也许按照abyx的建议,做一个包含多个匹配组的正则表达式会更好,然后根据匹配组捕获的子字符串来进行数学运算:
import re
example_data = """
this line will not match
abc 1 xyz 0
this line will not match
abc 2 xyz 1
abc 2 xyz 2 will not match
abc 3 xyz 2
"""
s_pattern = "abc (\d+) xyz (\d+)"
pat = re.compile(s_pattern)
# note that you can pre-compile the single pattern
# you cannot do that with the dynamic patterns
for match_group in re.finditer(pat, example_data):
n1 = int(match_group.group(1))
n2 = int(match_group.group(2))
if n1 > 0 and n1 == n2 + 1:
print match_group.group(0)
这段代码同样会输出:
abc 1 xyz 0
abc 2 xyz 1
abc 3 xyz 2
3
这段话的意思是,把 i
放到第一个 %s
的位置,然后把 i-1
放到第二个 %s
的位置。
re.match("abc %s xyz %s"%(i,i-1), data)
还有一种写法可以这样表示:
re.match("abc "+str(i)+" xyz "+str(i-1), data)