python re.sub 组 : number after\number

标签 python regex numbers regex-group

如何将 foobar 替换为 foo123bar

这不起作用:

>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'

这行得通:

>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'

我认为当有 \number 之类的内容时,这是一个常见问题。谁能给我一个关于如何处理这个问题的提示?

最佳答案

答案是:

re.sub(r'(foo)', r'\g<1>123', 'foobar')

文档的相关摘录:

In addition to character escapes and backreferences as described above, \g will use the substring matched by the group named name, as defined by the (?P...) syntax. \g uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.

关于python re.sub 组 : number after\number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5984633/

相关文章:

python - django.urls.exceptions.NoReverseMatch : Reverse for 'sign_up' not found. 'sign_up' 不是有效的 View 函数或模式名称

python - 多标签文本分类

Python SimpleKML 新点坐标替换

regex - 'optional' 量词 ('??' ) 的惰性版本在正则表达式中有用吗?

java - 使用正则表达式清理文本

Java:分割逗号分隔的字符串但忽略引号中的逗号

c# - C# 中的数字列表并获取最小值和最大值,而不保留上一个循环中存储的变量

java - 彩票程序 Java 比较两个数字

c++ - 制作具有平均值的随机数生成器

Python转换温度报错