正则表达式:删除未以特定字符为前缀的字符串

Regex: remove string that is not prefixed with a specific character

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

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

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

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

我试过使用 re.sub(r"[^:]\n", "", "key:\n value\n here\n") 但是,这并不是 return 想要的结果,而是 return 以下内容: "key:\n valu her"

如有任何帮助,我们将不胜感激。

你想要的是所谓的否定回顾断言。在 Python 的 re 中,它采用 (?<!...) 的形式,其中 ... 应该 而不是 落后于接下来发生的任何事情.

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