假设我有以下形式的 ASCII 文件中的一行:
{text1} {stringA} {text2} {stringB} {text3}
where {stringA}
and {stringB}
是感兴趣的子串。我们分别称它们为“A”和“B”。琴弦{text1}
, {text2}
, and {text3}
是不包含 A 或 B 的任意长度的字符串(可能为空)。
我想要在Python中做的只是交换A和B,使得该行从
{text1} {stringA} {text2} {stringB} {text3}
to
{text1} {stringB} {text2} {stringA} {text3}
如果有任何帮助,我将不胜感激。我认为通过获得关于这个问题的帮助,它将帮助我学习更好地使用 Python 中的正则表达式。
注意{text1}
, {text2}
, and {text3}
是未知的字符串。
我们确切地知道子串 A 和 B。我们知道在该行中 A 在 B 之前。然而,我们不知道它们之前/之间/之后是什么(如果有的话)。
示例(A=约翰,B=蒂姆):
(1) 这个:
“我告诉约翰把包交给蒂姆。”
改为这样:
“我告诉蒂姆把包交给约翰。”
(2)这个:
“约翰向蒂姆问好。”
改为这样:
“蒂姆向约翰打招呼。”
(3)这个:
“约翰!h9aghag蒂姆”
改为这样:
“蒂姆!h9aghag约翰”
>>> import re
>>> text = '{text1} {stringA} {text2} {stringB} {text3}'
>>> re.sub(r'(stringA)(.*)(stringB)', r'\3\2\1', text)
'{text1} {stringB} {text2} {stringA} {text3}'
Replace stringA
and stringB
使用您感兴趣的子字符串,请注意您可能想要re.escape()它们以防子字符串可以包含在正则表达式中具有特殊含义的字符。
测试用例:
>>> stringA = 'John'
>>> stringB = 'Tim'
>>> regex = re.compile(r'(%s)(.*)(%s)' % (stringA, stringB))
>>> regex.sub(r'\3\2\1', "I told John to give the bag to Tim.")
'I told Tim to give the bag to John.'
>>> regex.sub(r'\3\2\1', "John said hello to Tim.")
'Tim said hello to John.'
>>> regex.sub(r'\3\2\1', "John!h9aghagTim")
'Tim!h9aghagJohn'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)