如何使用 re.sub
划分群组?
我希望它覆盖3
具有另一个值
Current:
XYZ.Value = 3
;After:
XYZ.Value = 5
;
现在我的子看起来像这样:
name = XYZ
value = 5
content = XYZ.Value = 5
re.sub(r'(%s\.Value\s*=\s*)([^;]+)' %name, r'\1 ' + value, content)
这不起作用,因为它不断添加额外的空格 ' '
覆盖该值后:
XYZ.Value = 5;
<--- 2 whitespaces instead of 1
我还尝试使用分组 \g<2>
re.sub(r'(%s\.Value\s*=\s*)([^;]+)' %name, r'\1\g<2>' + value, content)
但随后它会继续添加现有值而不覆盖它:
Output:
XYZ.Value = 3
最佳答案
看来re.sub(r'(%s\.Value\s*=\s*)([^;]+)' %name, r'\g<1>' + value, content)
会做:
- 删除反向引用后面的空格,因为您已经捕获了
3
之前的所有空格。进入第 1 组,并且 - 使用明确的反向引用 (
\g<n>
),允许在其后使用任何数字。
请参阅Python demo :
import re
name = 'XYZ'
value = '5'
content = 'XYZ.Value = 5'
print(re.sub(r'(%s\.Value\s*=\s*)([^;]+)' %name, r'\g<1>' + value, content))
# => XYZ.Value = 5
关于python - 重新分组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36582824/