gpt4 book ai didi

python - 如果特定字符位于与 Python 中的模式匹配的字符串中,则替换该特定字符

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:00 25 4
gpt4 key购买 nike

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

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

我希望输出的是

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

re.sub(r'\$*\\*\$', 'X', b)$ 替换为 X .我应该如何用一个 re.sub 命令做到这一点?

最佳答案

您可以使用 lambdare.sub 使用 str.replace 替换任何 \\匹配你的模式

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]

关于python - 如果特定字符位于与 Python 中的模式匹配的字符串中,则替换该特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com