今天看python核心编程看到一个问题,题意大概就是过滤一个file-like对象里“#”的注释部分,然后输出其他部分。简单情形下,另写一行的#注释比较好判断,用startwith('#')匹配应该能满足。问题在于那些写在正常业务代码之后的注释,该如何过滤之?举个例子:
if name.find(",") == -1:#Annotations pass
请问有没有人了解它是怎么过滤这种注释的?谢谢。
Let’s talk about the ideaIf you don’t consider the # in the string, it is very convenient to use re to match
#
#[^\n]*?\n
is enoughIf you consider that the # in the string is slightly more complicated, match:
#[^'"]*?\n
Barely able to cope with most situations
The disadvantage is that for
'a' # 'b'
Such a statement cannot be matched because Python's re does not support balanced groups.
Just use regular matching#It won’t work until the end of the line.
Let’s talk about the idea
If you don’t consider the
#
in the string, it is very convenient to use re to matchis enough
If you consider that the
#
in the string is slightly more complicated, match:Barely able to cope with most situations
The disadvantage is that for
Such a statement cannot be matched because Python's re does not support balanced groups.
Just use regular matching
#
It won’t work until the end of the line.