在Python中,如果一个字符串匹配某个模式并且其中包含特定字符,则可以替换该特定字符。

3

如果匹配某个模式,是否可以使用正则表达式替换字符串中的特定字符?例如,如果一个\字符在两个$字符之间,我想将其替换为X,否则它应该保持不变。

 $some\string here inside$ and [some here \out side]

and what I expect to have in output is

$someXstring here inside$ and [some here \out side]

re.sub(r'\$*\\*\$', 'X', b)$ 替换为 X。如何使用一个 re.sub 命令完成此操作?

2个回答

3

您可以使用lambdastr.replacere.sub一起,替换任何符合您模式的\\

s = "$some\string here inside$ and [some here \out side]"
import re

print(re.sub(r"\$.*\\.*\$",lambda  x: x.group().replace("\\","X"),s))
$someXstring here inside$ and [some here \out side]

感激不尽 :) 谢谢 - Esildor

1
无正则表达式的解决方案:
s = r'$some\string here inside$ and [some here \out side]'

def solution(s):
    inside = False
    for c in s:
        if c == '$':
            inside = not inside
            yield c
        elif inside and c == '\\':
            yield 'X'
        else:
            yield c


print(''.join(solution(s)))

我知道一些解释会很受欢迎,但目前我不知道该解释什么。


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