You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python re模块编写正则匹配自定义格式的单行和多行注释

Python re 匹配两类自定义注释的正则方案

可用正则及使用方法

import re

# 匹配规则
pattern = r'#=(?:.*?=#|.*$)'
# 匹配时必须传入 re.DOTALL 标志,让 . 可以匹配换行符
# 可选传入 re.MULTILINE 标志适配多文本行尾匹配边界

匹配逻辑说明

  • 优先匹配多行注释:分支.*?=#采用非贪婪匹配,从#=开始匹配任意字符(含换行)直到遇到闭合标记=#
  • 兜底匹配单行注释:如果没有找到闭合标记=#,就匹配#=之后到当前行尾的所有内容
  • 非捕获组(?:)用来分组两个分支逻辑,不会额外产生不需要的捕获结果

原有正则的问题

你之前写的r'(#=)[\w ]*'存在两个明显限制:

  1. 字符匹配范围只覆盖了字母、数字、下划线和空格,遇到标点、特殊符号就会中断匹配
  2. 不支持匹配换行符,完全无法覆盖多行注释场景

测试示例

测试代码:

test_content = """
#= this is a single line comment
some code here
#= this is a 
multiline comment =#
other code here
#= another single line comment with special chars!@#
"""
matches = re.findall(pattern, test_content, flags=re.DOTALL | re.MULTILINE)
for m in matches:
    print("匹配到注释:", repr(m))

输出结果:

匹配到注释: '#= this is a single line comment'
匹配到注释: '#= this is a \nmultiline comment =#'
匹配到注释: '#= another single line comment with special chars!@#'

内容的提问来源于stack exchange,提问作者iiiasminx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:24:04