Python正则表达式使用特定条件替换语法跳过行



只有当一行满足特定条件时,我才想在字符串中进行替换。

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'),
('asn ','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

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

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

您还需要使用re.M(regex.M(标志来确保^匹配所有行的起始位置,而不仅仅是整个字符串的起始位置。请参阅Python演示:

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'(?<!^--.*)basn ','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

最新更新