简体   繁体   中英

replacing parts of string using regular expression match in python

In python, I have to replace every occurance of (a is b) with (a,b) [where a,b are non-null strings , observe that paranthesis are a part of substring] in a string s . I am planning to use re module .. but I am stuck with how to preserve a,b in the replacement string ..How can I do this?

Ex:  "you know that (tiger is animal) and kiwi is bird"
     output : "you know that (tiger,animal) and kiwi is bird"

matching regex is :

 r"\([a-z]+\sis\s[a-z]+\)"

re is a better solution for your case:

>>> 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'

See break-out of regex here with different examples.

您可以使用

re.sub(r'(^\([^\s]+)\s+is\s+(.+$)', r'\1,\2', input)

使用捕获组和反向引用:

re.sub(r"\(([a-z]+)\sis\s([a-z]+)\)", r"(\1,\2)", text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM