我正在尝试使用Python提取c代码的“非注释”部分。到目前为止,我的代码可以在这些示例中提取"non_comment“,如果找不到,它只返回"”
// comment
/// comment
non_comment;
non_comment; /* comment */
non_comment; // comment
/* comment */ non_comment;
/* comment */ non_comment; /* comment */
/* comment */ non_comment; // comment
下面是源代码,我使用doctest对不同的场景进行单元测试
import re
import doctest
def remove_comment(expr):
"""
>>> remove_comment('// comment')
''
>>> remove_comment('/// comment')
''
>>> remove_comment('non_comment;')
'non_comment;'
>>> remove_comment('non_comment; /* comment */')
'non_comment;'
>>> remove_comment('non_comment; // comment')
'non_comment;'
>>> remove_comment('/* comment */ non_comment;')
'non_comment;'
>>> remove_comment('/* comment */ non_comment; /* comment */')
'non_comment;'
>>> remove_comment('/* comment */ non_comment; // comment')
'non_comment;'
"""
expr = expr.strip()
if expr.startswith(('//', '///')):
return ''
# throw away /* ... */ comment, and // comment at the end
pattern = r'(/\*.*\*/\W*)?(\w+;)(//|/\*.*\*/\W*)?'
r = re.search(pattern, expr)
return r.group(2).strip() if r else ''
doctest.testmod()
然而,不知何故,我不喜欢这些代码,我相信应该有更好的方法来处理这个问题。有没有人知道更好的方法呢?谢谢!
发布于 2018-08-01 05:18:25
https://stackoverflow.com/questions/51621936
复制相似问题