Python正则表达式无法替换整行

时间:2017-02-25 14:15:21

标签: python regex python-3.x

我正在尝试替换文本行中的特定区域。 我使用了python正则表达式子语法

import re
str='WALL = "W101"'
s=re.sub('WALL = "(.*)"','100',str)
print(s)

它仅打印100但是 我期待整行WALL = "100"

2 个答案:

答案 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