python - 如何区分组引用和后面的数字?

标签 python regex

我正在尝试替换字符串中所有出现的特定数字。例如,假设我想用另一个替换给定数字的特定实例:

>>> number1 = 33
>>> number2 = 1
>>> re.sub('(foo)%i' % number1, '\\1%i' % number2, 'foo33')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/david_clymer/Development/VistaShare/ot_git/lib/python2.4/sre.py", line 142, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "/home/david_clymer/Development/VistaShare/ot_git/lib/python2.4/sre.py", line 260, in filter
    return sre_parse.expand_template(template, match)
  File "/home/david_clymer/Development/VistaShare/ot_git/lib/python2.4/sre_parse.py", line 784, in expand_template
    raise error, "invalid group reference"
sre_constants.error: invalid group reference
>>> re.sub('(foo)%i' % number1, '\\1 %i' % number2, 'foo33')
'foo 1'

我怎样才能避免将组引用与以下数字混为一谈?

最佳答案

import re

number1 = 33
number2 = 1
print re.sub('(foo)%i' % number1, '\g<1>%i' % number2, 'foo33')

re.sub(pattern, repl, string, count=0, flags=0)

In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> 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.

http://docs.python.org/2/library/re.html#module-re

关于python - 如何区分组引用和后面的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15168249/

相关文章:

python - 在字典中插入值时出现问题

regex - 在CMake中将字符串的一部分转换为大写

java - 匹配所有出现的正则表达式 Java

javascript - 使用 Javascript 和 Jquery 从 HTML 中转义括号

python - 根据字符的出现对列表进行排序

python - 如何保存到变量中指定的字段?

regex - 字符串匹配版本格式

java - 在拼字游戏词典中搜索带有空白图 block ("") 字符的单词

python - 如何按时间顺序使用multiprocessing?

Python UPnP/IGD 客户端实现?