【问题标题】:Python regex substitute syntax skip lines with certain criteriaPython 正则表达式用某些条件替换语法跳过行
【发布时间】: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)

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

-- from text some text
-- with text

【问题讨论】:

  • (?<!^--.*) 添加到每个正则表达式并使用PyPi regex 模块,而不是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)使用链接中的代码。 使用 PyPi regex 模块,而不是 re

标签: python regex substitution python-re


【解决方案1】:

您可以使用 PyPi regex 模块使用纯正则表达式来解决这个问题。转到控制台/终端并运行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

【讨论】:

  • 对于不区分大小写的--跳过,(?i)会在r'(?&lt;!^--.*)中使用吗?
  • 类似-- WITH text第一个实例的缩进
  • @paranormaldist 如果您只需要对选定的项目使用不区分大小写的搜索,您可以在模式的开头使用(?i),例如r'(?i)(?&lt;!^--.*)\bwith '
  • 我在使用这一行时遇到问题-- WITH text 无论是否不区分大小写,它都不会跳过@Wiktor Stribiżew
  • @paranormaldist 我明白了,这些是多行文档中的行,所以你也需要regex.M 标志,使用flags=regex.I | regex.M
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多