我正在解析文本,我想在其中進行更改,但僅限於特定行。只替換匹配表達式中的特定組
我有一個正則表達式模式,捕捉整條線,如果它是一條感興趣的線,並且在表達式中我有一個記憶中的組,我真的想改變它。
我想只能在匹配的表達式中更改特定的組,而不是替換整個表達式(將替換整個行)。
例如:
我有一個文本文件:
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)
不會做的工作。
提前感謝!
您不能選擇使用替代雖然。 – Moondra 2017-08-14 22:52:42