【问题标题】:Regex: remove string that is not prefixed with a specific character正则表达式:删除不以特定字符为前缀的字符串
【发布时间】:2021-03-18 10:04:15
【问题描述】:

使用正则表达式,有没有办法删除不以特定前缀开头的字符?

例如(更具体地说),在下面的字符串中,我只想删除不紧跟分号的换行符:

初始字符串: "key:\\n value\\n here\\n"

所需的输出字符串(结果) "key:\\n value here"

我尝试过使用re.sub(r"[^:]\\n", "", "key:\\n value\\n here\\n") 但是,这不会返回所需的结果,而是返回以下内容:"key:\\n valu her"

任何帮助将不胜感激。

【问题讨论】:

    标签: python regex re


    【解决方案1】:

    您想要的称为否定的后向断言。在 Python 的re 中,它采用(?<!...) 的形式,其中...应该出现在后面的东西。

    >>> s = "key:\\n value\\n here\\n"
    >>> re.sub(r"(?<!:)\\n", "", s)
    'key:\\n value here'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多