Python 正则表达式替换语法跳过符合特定条件的行

Python regex substitute syntax skip lines with certain criteria

我想仅当该行满足特定条件时才在字符串中进行替换。

text_old = """
with some text 
some text as(
-- from text some text
with select text some other text
-- with text
from text
"""

我的替换是 -

replacements = [
    ('with ','with \n'),
    ('as\n ','as'), 
    ('as\(','as (') 
        ]
for old, new in replacements:
    text_new = re.sub(old,new,text_old,flags=re.IGNORECASE)

如果该行以 -- 开头,我想跳过替换。所以这里跳过 fromwith 替换 -

-- from text some text
-- with text

您可以使用 PyPi regex 模块使用纯正则表达式解决此问题。转到 console/terminal 和 运行 pip install regex 命令。这将允许您在脚本中 import regex,剩下要做的就是将 (?<!^--.*) 添加到每个正则表达式:

replacements = [
    (r'(?<!^--.*)\bwith ','with \n'),
    (r'(?<!^--.*)\bas\n ','as'), 
    (r'(?<!^--.*)\bas\(','as (') 
]

您还需要使用 re.M (regex.M) 标志来确保 ^ 匹配所有行的开始位置,而不仅仅是整个字符串的开始。 见 Python demo:

import regex as re

text_old = """
with some text 
some text as(
-- from text some text
with select text some other text
-- with text
from text
"""

replacements = [
    (r'(?<!^--.*)\bwith ','with \n'),
    (r'(?<!^--.*)\bas\n ','as'), 
    (r'(?<!^--.*)\bas\(','as (') 
]
text_new = text_old
for old, new in replacements:
    text_new = re.sub(old,new,text_new,flags=re.I|re.M)

print(text_new)

输出:


with 
some text 
some text as (
-- from text some text
with 
select text some other text
-- with text
from text