带有标志的 Python re.sub 不会替换所有出现

标签 python regex

Python 文档说:

re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...

那么当我得到以下意外结果时是怎么回事?

>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'

最佳答案

re.sub的定义:

re.sub(pattern, repl, string[, count, flags])

第 4 个参数是计数,您使用 re.MULTILINE(即 8)作为计数,而不是作为标志。

要么使用命名参数:

re.sub('^//', '', s, flags=re.MULTILINE)

或者先编译正则表达式:

re.sub(re.compile('^//', re.MULTILINE), '', s)

关于带有标志的 Python re.sub 不会替换所有出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42581/

相关文章:

python - 将配对数据 append 到列表的最快方法

python Pandas : transform dataframe adding grouped columns

java性能问题-正则表达式VS内部String方法

java - 使用 java/regex 查找最后一个匹配项

javascript - 如何用 javascript 中以特殊字符开头的单词内的空格替换下划线?

regex - 如何从这个键值对中提取值?

python - 如何将索引列表转换为二进制数?

Python - 查找列表中匹配条件的下一个元素。替换之前的条目

python - 如何使用 ^ 和 $ 来解析简单的表达式?

python tarfile错误: struct.错误:解包需要长度为4的字符串参数