Python re 中评论的正则表达式

Regular expression for comments in Python re

我希望能够使用标准库中的 re 模块通过正则表达式识别注释。问题是我的行和多行注释有相同的开始。

One-line comment:
#= this is a coment

some code here

#= this is a 
multiline comment =#

并且我一直在尝试获得一个(或多个)正则表达式以便能够同时捕获它们。单行注释我得到了r'(#=)[\w ]*',但是多行注释一直不成功

你能帮我解决这个问题吗?

评论中已经指出这种语法不理想。 但是,您可以使用否定前瞻来解析您的评论:

import re
s = """uniline comment:
#= this is a coment

some code here

#= this is a 
multiline comment =#

#=single comment at the end"""

pattern = re.compile(r'#=(?:(?!#=).)*?=#|#=.*?(?=\n|$)', re.DOTALL)
result = re.findall(pattern, s)
print(result)
  • #=(?:(?!#=).)*?=# 捕获 #= 和下一个 =# 之间的所有内容(多行注释)。我们排除 #= 以避免在我们的多行匹配中捕获单行注释。
  • #=.*?(?=\n|$) 捕获单行注释($ 确保即使在文件末尾也捕获单行注释)

demo