【发布时间】:2021-03-26 19:08:46
【问题描述】:
只有当行满足特定条件时,我才想在字符串中进行替换。
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)
如果该行以 -- 开头,我想跳过替换。所以 from 和 with 替换在这里被跳过 -
-- from text some text
-- with text
【问题讨论】:
-
将
(?<!^--.*)添加到每个正则表达式并使用PyPiregex模块,而不是re。只需pip install regex然后import regex as re并使用您的re.sub... -
@WiktorStribiżew 在
replacements中添加语法? -
@WiktorStribiżew 我确实收到了一个错误
error: look-behind requires fixed-width pattern,这可能是由于间距造成的吗? if ``` --``` vs--,虽然我不这么认为 -
我写了如何做到这一点:1)
pip install regex在终端/控制台中安装 PyPi 正则表达式模块,然后 2)使用链接中的代码。 使用 PyPiregex模块,而不是re。
标签: python regex substitution python-re