我有
的字符串输入s = 'horse dog cat bear'
我希望将单词的顺序更改为
cat horse dog bear
相应的re
将是
>>> import re
>>> s = 'horse dog cat bear'
>>> print re.sub(r'(horse )(dog )?(cat )(bear)', r'\3\1\2\4', s)
cat horse dog bear
我使用了(dog )?
,因为当dog
不存在时我还想匹配字符串。因此输出应为cat horse bear
。但是当我尝试时,我遇到了以下错误 -
>>> s = 'horse cat bear'
>>> print re.sub(r'(horse )(dog )?(cat )(bear)', r'\3\1\2\4', s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib/python2.7/re.py", line 291, in filter
return sre_parse.expand_template(template, match)
File "/usr/lib/python2.7/sre_parse.py", line 831, in expand_template
raise error, "unmatched group"
sre_constants.error: unmatched group
>>>
即使dog
不存在,我怎样才能获得输出?
答案 0 :(得分:2)
尝试
r'(horse )((?:dog )?)(cat )(bear)'
即。使捕获组的内容可选,而不是组本身。
答案 1 :(得分:0)
您需要使用re
吗?你可以用列表来做。
s0 = 'horse dog cat bear'
s1 = 'horse cat bear'
s_map = 'cat horse dog bear'.split()
print(" ".join([x for x in s_map if x in s0.split()]))
print(" ".join([x for x in s_map if x in s1.split()]))
输出:
cat horse dog bear
cat horse bear