这里有一个例子:
import re
io = [
('my name is (?P<name>\w+)', 'Hi there, {name}'),
]
string = input('> ')
for regex, output in io:
match = re.match(regex, string)
if match:
print(output.format(**match.groupdict()))
break
我来带你一起看:
'my name is (?P<name>\w+)'
(?P<name>...)
会将后面的部分 (\w+
) 存储在匹配对象中,我们稍后会使用到,存储时会用指定的名称 name
进行标识。
match = re.match(regex, string)
这个函数在给定的输入中查找regex
。请注意,re.match
只匹配输入的开头,如果您不想受此限制,请改用re.search
。
如果匹配成功:
output.format(**match.groupdict())
`match.groupdict` 返回一个由 `(?P...)` 定义的键和它们对应的匹配值组成的字典。`**` 将这些键/值传递给 `.format`,在此情况下,Python 将其转换为 `output.format(name='matchedname')`。
要从文件中构建 `io` 字典,请执行以下操作:
io = []
with open('input.txt') as file_:
for line in file:
key, value = line.rsplit(' | ', 1)
io.append(tuple(key, value))