正则表达式替换成对的美元符号

时间:2016-07-28 19:30:58

标签: python regex

我有一个字符串:The old man $went$ to the $barn$.如何将其转换为The old man ~!went! to the ~!barn!.

如果我不需要在第一次出现之前添加~,我可以在Python中执行text.replace('$', '!')

3 个答案:

答案 0 :(得分:1)

使用捕获组,以便替换字符串可以将$之间的文本放回原位。

所以正则表达式是:

\$([^$]*)\$

然后替换字符串将是:

~!\1!

Regex101 Demo

答案 1 :(得分:1)

是的,正则表达式。捕获小组将提供帮助。

result = re.sub(r'\$(.*?)\$', r'~!\1!', my_str)

答案 2 :(得分:1)

可能正则表达式捕获组是这里的方法,但这里有一个简单的方法来做到没有正则表达式:

>>> s
'The old man $went$ to the $barn$'
>>> r
''
>>> seen = False
>>> 
>>> for c in s:
        if c=='$':
            if seen:
                r +='!'
                seen = False
            else:
                r +='~!'
                seen=True
        else:
            r += c


>>> r
'The old man ~!went! to the ~!barn!'
相关问题