regex - 如何用数字和捕获组替换字符串?
问题描述
我有一个包含一个数字的字符串,我想用另一个数字替换它并保留字符串的其余部分。
例如,
原创 =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
。
如何将文字数字与替换字符串中的组标识符分开定义?
解决方案
这是一种方法。
前任:
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
推荐阅读
- swift - 通用集合上的 Swift 编译器段错误
- reactjs - 反应存储组件的状态,道具不更新
- r - 处理大量行
- python - 如何编写while循环以使其在2个变量获得某些值时停止?(Python)
- sql - 转换之间的左连接导致行数减少
- javascript - Electron-builder 托盘图标未显示(Linux Mint 20、electronjs 11、electron-builder 22)
- c - While循环打印两次而不扫描
- android - 如何从带有持有人的网址显示图像视图
- python-3.x - subprocess.run().stdout.read() 返回 CompletedProcess 不是字符串
- c# - DotNetCore 日志中的 [40m[32minfo[39m[22m[49m] 是什么意思