在python中使用正则表达式匹配替换字符串的部分
在python中, 我必须用在python中使用正则表达式匹配替换字符串的部分,python,regex,Python,Regex,在python中, 我必须用(a,b)替换字符串s中出现的(a,b)[其中a,b是非空字符串,请注意,偏执是子字符串的一部分]。 我计划使用re模块。。但是我一直在研究如何在替换字符串中保留a,b。,我该怎么做呢 Ex: "you know that (tiger is animal) and kiwi is bird" output : "you know that (tiger,animal) and kiwi is bird" 匹配的正则表达式是: r"\([a-z]+\s
(a,b)
替换字符串s中出现的(a,b)
[其中a,b是非空字符串,请注意,偏执是子字符串的一部分]。
我计划使用re
模块。。但是我一直在研究如何在替换字符串中保留a,b。,我该怎么做呢
Ex: "you know that (tiger is animal) and kiwi is bird"
output : "you know that (tiger,animal) and kiwi is bird"
匹配的正则表达式是:
r"\([a-z]+\sis\s[a-z]+\)"
你可以用
re.sub(r'(^\([^\s]+)\s+is\s+(.+$)', r'\1,\2', input)
使用捕获组和反向引用:
re.sub(r"\(([a-z]+)\sis\s([a-z]+)\)", r"(\1,\2)", text)
re
是一个更好的解决方案:
>>> pat_sub = re.compile(r'(?<=\()\s*?(?P<X>[a-z]+)\s*?is\s*?(?P<Y>[a-z]+)\s*?(?=\))')
>>>
>>> pat_sub.sub(r'\g<X>,\g<Y>',s)
'you know that (tiger,animal) and kiwi is bird'
>>>
>>> s
'you know that (tiger is animal) and kiwi is bird'
>>pat_sub=re.compile(r'(?Ah..那么在这种情况下,re
是一个更好的解决方案,因为它将使用内置方法增加代码的复杂性。