Home  >  Q&A  >  body text

python是怎么实现过滤 #注释代码的?

今天看python核心编程看到一个问题,题意大概就是过滤一个file-like对象里“#”的注释部分,然后输出其他部分。简单情形下,另写一行的#注释比较好判断,用startwith('#')匹配应该能满足。问题在于那些写在正常业务代码之后的注释,该如何过滤之?举个例子:

if name.find(",") == -1:#Annotations
    pass

请问有没有人了解它是怎么过滤这种注释的?谢谢。

巴扎黑巴扎黑2741 days ago543

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 10:31:44

    Let’s talk about the idea
    If you don’t consider the # in the string, it is very convenient to use re to match

    #[^\n]*?\n

    is enough
    If 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.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:31:44

    Just use regular matching#It won’t work until the end of the line.

    reply
    0
  • Cancelreply