我正在尝试替换文本行中的特定区域。 我使用了python正则表达式子语法
import re
str='WALL = "W101"'
s=re.sub('WALL = "(.*)"','100',str)
print(s)
它仅打印100
但是
我期待整行WALL = "100"
答案 0 :(得分:0)
考虑第一个子字符串的其他捕获组:
str = 'WALL = "W101"'
s = re.sub(r'^(WALL =\s*)"(.*)"', r'\1"100"', str)
print(s)
输出:
WALL = "100"
\1
指向带有正则表达式的第一个捕获组
答案 1 :(得分:0)
您可以使用lookbehind:
import re
str = 'WALL = "W101"'
s = re.sub(r'(?<=WALL = ")[^"]+', '100', str)
print(s)
<强>解释强>
(?<= : start lookbehind, makes sure we have the following before the match
WALL = " : literally
) : end lookbehind
[^"]+ : 1 or more character that is NOT a double quote