Skip to main content
 首页 » 编程设计

python之使用 python 从源文件中剥离 C/C++ 注释

2025年05月04日13me-sa

我有一个忽略以/* ... */开头的多行注释的正则表达式 但不适用于以//

开头的行

有人可以建议在此正则表达式中添加什么以使其忽略

pattern = r""" 
                        ##  --------- COMMENT --------- 
       /\*              ##  Start of /* ... */ comment 
       [^*]*\*+         ##  Non-* followed by 1-or-more *'s 
       (                ## 
         [^/*][^*]*\*+  ## 
       )*               ##  0-or-more things which don't start with / 
                        ##    but do end with '*' 
       /                ##  End of /* ... */ comment 
     |                  ##  -OR-  various things which aren't comments: 
       (                ##  
                        ##  ------ " ... " STRING ------ 
         "              ##  Start of " ... " string 
         (              ## 
           \\.          ##  Escaped char 
         |              ##  -OR- 
           [^"\\]       ##  Non "\ characters 
         )*             ## 
         "              ##  End of " ... " string 
       |                ##  -OR- 
                        ## 
                        ##  ------ ' ... ' STRING ------ 
         '              ##  Start of ' ... ' string 
         (              ## 
           \\.          ##  Escaped char 
         |              ##  -OR- 
           [^'\\]       ##  Non '\ characters 
         )*             ## 
         '              ##  End of ' ... ' string 
       |                ##  -OR- 
                        ## 
                        ##  ------ ANYTHING ELSE ------- 
         .              ##  Anything other char 
         [^/"'\\]*      ##  Chars which doesn't start a comment, string 
       )                ##    or escape 
    """ 

请您参考如下方法:

如果您计划使用当前的正则表达式,可以执行以下操作来匹配 //... 注释:

在此之下:

 /                ##  End of /* ... */ comment 

添加这个:

 |                  ## OR it is a line comment with // 
  \s*//.*           ## Single line comment 

参见 demo