我正在解析我想进行更改的文本,但仅限于特定行。
我有一个正则表达式模式,如果它是感兴趣的行,它会捕获整行,并且在表达式中我记住了一组我实际上想要更改的内容。
我希望能够仅更改匹配表达式中的特定组,而不是替换整个表达式(那将替换整行)。
例如:
我有一个文本文件:
This is a completely silly example.
something something "this should be replaced" bla.
more uninteresting stuff
我有正则表达式: pattern = '.*("[^"]*").*'
然后我捕获了第二行,但我只想替换该行内的 "this should be replaced" 匹配组,而不是整行。 (所以使用 re.sub(pattern, replacement, string) 不会完成这项工作。
提前致谢!
请您参考如下方法:
有什么问题
r'"[^"]+"'
匹配表达式前后的 .* 也匹配零长度字符串,因此您根本不需要它。
re.sub(r'"[^"]+"', 'DEF', 'abc"def"ghi')
# returns 'abcDEFghi'
您的示例文本将导致:
'This is a completely silly example.\nsomething something DEF bla.\nmore uninteresting stuff
