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

2024-05-15 00:51:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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.'

Tags: oftherestringquickatovermultiline
3条回答
re.sub('(?m)^//', '', s)

^{}的完整定义是:

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

这意味着,如果告诉Python参数是什么,那么就可以传递flags,而不传递count

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

或者,更简洁地说:

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

看看^{}的定义:

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

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

请使用命名参数:

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

或者先编译regex:

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

相关问题 更多 >

    热门问题