正则表达式搜索和替换:如何在文本块中移动字符

3
我正在遇到一个搜索和替换的问题。看这个例子:
我想要从:
"Word1 word2 =word3 *word4 word5= word6 word7* (*word8)"

翻译成中文为:这样做:
"Word1 word2 word3= word4* word5= word6 word7* word8*"

即:将任何以 * 或 = 开头的单词替换为将 * 或 = 移至单词末尾,并且有时这些单词在括号中,或者可能在行的开头或结尾。我已经尝试搜索解决方案,但我对正则表达式相对陌生,虽然我可以拼凑出找到我要查找的单词的解决方案,例如:
\[\*,\=][a-zA-Z]{1,}[\s,\)]

我不知道如何替换和保留行尾/行首字符、空格和括号。我正在使用Python,但如果有什么区别的话,我很乐意尝试其他语言。
2个回答

3
你需要两个捕获组并将它们结合起来替换:
>>> import re
>>> 
>>> s = "Word1 word2 =word3 *word4 word5= word6 word7* (*word8)"
>>>
>>> re.sub(r'(\*|=)(\b\w+\b)', r'\2\1', s)
'Word1 word2 word3= word4* word5= word6 word7* (word8*)'

2

使用如下详细的表达方式:

import re
rx = re.compile('''
    \(?    # opening parenthesis or not
    ([*=]) # capture one of * or = to Group 1
    (\w+)  # at least one word chararacter to Group 2
    \)?    # a closing parenthesis
''', re.VERBOSE)

string = "Word1 word2 =word3 *word4 word5= word6 word7* (*word8)"
new_string = rx.sub(r'\2\1', string)

请参见ideone.com上的演示,并根据需要在方括号中添加其他字符以完善该类。

工作完美,我甚至认为我已经理解了它,非常感谢! - user3652142

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接