【问题标题】:Regular expression to remove all lines that begin with a specific symbol and more正则表达式删除以特定符号等开头的所有行
【发布时间】:2021-11-09 21:12:45
【问题描述】:

我想使用正则表达式删除所有以 '!' 开头的行,但以该字符开头的最后一行除外。此外,应删除所有空行。

!第 1 行

!即第 2 行

! - 另一行

! a b c d

0 1 2 3

4 5 6 7

8 9 10 11

想要的输出:

a b c d

0 1 2 3

4 5 6 7

8 9 10 11

到目前为止,我得到了:

re.sub(r'(?m)^(?!.*a\sb\sc\sd)\#.*\n?', '', textstring)

【问题讨论】:

    标签: python regex expression line


    【解决方案1】:

    你可以使用

    re.sub(r'\A(?:!.*\n)+!\s*(.*a\sb\sc\sd)', r'\1', textstring)
    

    this regex demo详情

    • \A - 字符串开头
    • (?:!.*\n)+ - 以! 开头的一行或多行
    • ! - 一个!
    • \s* - 零个或多个空格
    • (.*a\sb\sc\sd) - 第 1 组:除换行符之外的任何零个或多个字符,a、空格、b、空格、c、空格、d

    替换的是第 1 组的值,\1

    【讨论】:

      【解决方案2】:

      (?:.*\n)+!([^!]*)

      您可以在https://regex101.com/进行测试

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-08
        • 1970-01-01
        • 2020-12-13
        • 2014-01-10
        相关资源
        最近更新 更多