Python re.sub 将部分字符串更改为 ascii

标签 python regex

test1 = "<test>222</test>blah blah blah"
newVal = "222"
mstring = "(<test>).*(</test>)"
newString = re.sub(mstring,rf"\1{newVal}\2",test1)
print(newString)

我试图在字符串中查找特定值,并使用 re.sub 函数替换为不同的字符串。似乎我找到了正确的匹配项并且替换正在工作,但是 python 正在将字符串的一部分转换为其 ascii 等效值。您能帮我处理上面的代码吗,以便我生成以下输出

<test>222</test>blah blah blah

相反,我得到的结果低于

R2</test>blah blah blah

最佳答案

这是一个可能的解决方案:

test1 = "<test>222</test>blah blah blah"
newVal = "111"
mstring = "(<test>).*(</test>)"
newString = re.sub(mstring, f'\g<1>{newVal}\g<2>', test1)`
print(newString) # <test>111</test>blah blah blah

您的方法适用于 newVal例如,一个字母:

newVal = "a"
re.sub(mstring, f'\1{newVal}\2', test1) # <test>a</test>blah blah blah

这种奇怪的行为是由于 \1{newVal} (带有 newVal=333 )将被解释为对组 1333 的引用。 \g<1>语法相当于 \1 ,但在替换中并不含糊。

关于Python re.sub 将部分字符串更改为 ascii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58769952/

相关文章:

Python 如何提高 numpy 数组性能?

regex - 需要构建一个 REGEX 来放置在 javascript 中

javascript - 如何在javascript中将多个单词替换为单个单词?

regex - 如何在 Notepad++ 中将带连字符的单词与正则表达式合并?

python - 带有 block 字符的终端中的文本进度条

在 guard 和 result 中具有相同功能的 Python 列表理解

python - 更改箭袋的轴刻度 - Python

python - 在 Id 和年份上合并两个数据框 pandas,其中年份缺少值

r - 分成列,将连续的分隔符视为一个

.net - 为什么 regex.IsMatch(str) 比 str.EndsWith(不变文化)快?