我有一个字符串我试图匹配文本,它按预期工作
import re
s = "This week end is very good"
v = re.findall(r'(This)',s)
print v
输出:
['This']
但是当我尝试进行多次匹配时,它无法正常工作
import re
s = "This week end is very good"
v = re.findall(r'(This)(week)',s)
print v
输出:
[]
如何进行多重匹配,我希望输出像键值对
示例输出:
"This" : "week"
答案 0 :(得分:1)
您必须匹配空格字符。试试这个:
v = re.findall(r'(This) (week)',s)
结果:
v = re.findall(r'(This) (week)',s)
print v
[('This', 'week')]
要将其转换为键值对,只需调用dict
构造函数:
d = dict(v)
print d
{'This': 'week'}
答案 1 :(得分:1)
如果要使用多种搜索模式,则需要使用交替运算符|
。
>>> s = "This week end is very good"
>>> v = re.findall(r'This|week',s)
>>> ' : '.join(v)
'This : week'