带有标志的 Python re.sub 不会替换所有出现的 [英] Python re.sub with a flag does not replace all occurrences
问题描述
Python 文档说:
<块引用>re.MULTILINE:指定时,模式字符 '^' 匹配字符串的开头和每行的开头(紧跟在每个换行符之后)...默认情况下,'^' 仅匹配开头字符串...
那么当我得到以下意想不到的结果时发生了什么?
<预><代码>>>>进口重新>>>s = """//敏捷的棕色狐狸....//跳过了懒狗.""">>>re.sub('^//', '', s, re.MULTILINE)' 敏捷的棕色狐狸.\n//跳过了懒狗.'看re.sub
:
re.sub(pattern, repl, string[, count, flags])
第四个参数是计数,您使用 re.MULTILINE
(即 8)作为计数,而不是标志.
要么使用命名参数:
re.sub('^//', '', s, flags=re.MULTILINE)
或者先编译正则表达式:
re.sub(re.compile('^//', re.MULTILINE), '', s)
The Python docs say:
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...
So what's going on when I get the following unexpected result?
>>> 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.'
Look at the definition of re.sub
:
re.sub(pattern, repl, string[, count, flags])
The 4th argument is the count, you are using re.MULTILINE
(which is 8) as the count, not as a flag.
Either use a named argument:
re.sub('^//', '', s, flags=re.MULTILINE)
Or compile the regex first:
re.sub(re.compile('^//', re.MULTILINE), '', s)
这篇关于带有标志的 Python re.sub 不会替换所有出现的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!