带有标志的 Python re.sub 不会替换所有出现的情况
- 2025-01-03 08:40:00
- admin 原创
- 91
问题描述:
Python 文档说:
re.MULTILINE:指定时,模式字符 '^' 与字符串的开头和每行的开头(紧跟在每个换行符之后)匹配...默认情况下,'^' 仅与字符串的开头匹配...
那么当我得到以下意外结果时,发生了什么?
>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.
// Jumped over the lazy dog.'
解决方案 1:
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)
解决方案 2:
re.sub('(?m)^//', '', s)
解决方案 3:
的完整定义re.sub
是:
re.sub(pattern, repl, string[, count, flags])
这意味着如果你告诉 Python 参数是什么,那么你可以flags
不传递就传递count
:
re.sub('^//', '', s, flags=re.MULTILINE)
或者更简洁地说:
re.sub('^//', '', s, flags=re.M)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD