python - 使用正则表达式从源文件中删除注释

标签 python regex string

我正在编写一个程序来自动编写一些 C 代码,(我正在编写将字符串解析为具有相同名称的枚举) C 对字符串的处理不是很好。 所以一直有人唠叨我要试试python。

我制作了一个应该删除 C 风格 /* COMMENT *///COMMENT 的函数 从一个字符串: 代码如下:

def removeComments(string):
    re.sub(re.compile("/\*.*?\*/",re.DOTALL ) ,"" ,string) # remove all occurance streamed comments (/*COMMENT */) from string
    re.sub(re.compile("//.*?\n" ) ,"" ,string) # remove all occurance singleline comments (//COMMENT\n ) from string

所以我尝试了这段代码。

str="/* spam * spam */ eggs"
removeComments(str)
print str

它显然什么也没做。

关于我做错了什么有什么建议吗?

有句话我听过几次:

If you have a problem and you try to solve it with Regex you end up with two problems.


编辑: 多年以后再回首。 (经过相当多的解析经验)

我认为正则表达式可能是正确的解决方案。 这里使用的简单正则表达式“足够好”。 我在问题中可能没有足够强调这一点。 这是针对单个特定文件的。这没有棘手的情况。 我认为让正则表达式解析的文件足够简单,而不是将正则表达式复杂化为不可读的符号汤,维护工作要少得多。 (例如,要求文件只使用 // 单行注释。)

最佳答案

"//引号内的类似注释的字符串"怎么样?

OP 正在询问如何使用正则表达式来做到这一点;所以:

def remove_comments(string):
    pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
    # first group captures quoted strings (double or single)
    # second group captures comments (//single-line or /* multi-line */)
    regex = re.compile(pattern, re.MULTILINE|re.DOTALL)
    def _replacer(match):
        # if the 2nd group (capturing comments) is not None,
        # it means we have captured a non-quoted (real) comment string.
        if match.group(2) is not None:
            return "" # so we will return empty to remove the comment
        else: # otherwise, we will return the 1st group
            return match.group(1) # captured quoted-string
    return regex.sub(_replacer, string)

删除:

  • /* 多行注释 */
  • //单行注释

不会删除:

  • String var1 = "这是/*不是注释。*/";
  • char *var2 = "this is//也不是注释。";
  • url = 'http://not.comment.com';

注意:这也适用于 Javascript 源代码。

关于python - 使用正则表达式从源文件中删除注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2319019/

相关文章:

属性中的 Javascript 正则表达式

java - 如何将字符串排序到映射中并打印结果

python - 如何划分存储在 Python 变量中的两个整数?

python - 异步执行时的 AWS Lambda 回调

regex - Excel VBA正则表达式错误

regex - express js路由匹配不以字符串开头的url

c++ - ostringstream 给了我隐式实例化错误

C缓冲区溢出

python - 将列值转换为列?

python - 具有交叉熵损失的 Softmax 激活导致两个类别的输出分别准确地收敛于 0 和 1