首页 > 解决方案 > 如何用数字和捕获组替换字符串?

问题描述

我有一个包含一个数字的字符串,我想用另一个数字替换它并保留字符串的其余部分。

例如,

原创 =VAR token 3

修改=VAR token 1 // orig = 3

thetoken可以是任何字符串,语句始终以 the 开头并在其值VAR之间包含空格。token

我正在使用这个函数和正则表达式

import re

def modify(line, token, new_value):
    newline = re.sub(r'(^(\s*VAR\s*%s\s+)(\d+)(.*)' % token, r'\1%s // orig = \2\3' % new_value, line)
    print(newline)

运行此代码时收到错误消息

modify("VAR T    3", "T", "1")

Traceback (most recent call last):
  File "/usr/local/python/3.4.3_wTclTk/lib/python3.4/sre_parse.py", line 866, in expand_template
    literals[index] = s = g(group)
IndexError: no such group

<Stack Trace>
sre_constants.error: invalid group reference

我认为这是因为替换字符串实际上是变为r'\11 // orig = \2\3'并且没有 group 11

如何将文字数字与替换字符串中的组标识符分开定义?

标签: regexpython-3.x

解决方案


这是一种方法。

前任:

import re

def modify(line, token, new_value):
    newline = re.sub(r'^(VAR\s*)({}\s*)(\s+)(\d+)'.format(token), r'\1\2 {} // orig = \4'.format(new_value), line)
    print(newline)

modify("VAR T    3", "T", "1")

输出:

VAR T    1 // orig = 3

推荐阅读