Roe*_*ler 4 python regex parsing comments
我正在解析源代码文件,我想删除所有行注释(即以"//"开头)和多行注释(即/ .... /).但是,如果多行注释中至少有一个换行符(\n),我希望输出只有一个换行符.
例如,代码:
qwe /* 123
456
789 */ asd
Run Code Online (Sandbox Code Playgroud)
应该完全变成:
qwe
asd
Run Code Online (Sandbox Code Playgroud)
而不是"qweasd"或:
qwe
asd
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?谢谢
编辑:测试的示例代码:
comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
Run Code Online (Sandbox Code Playgroud)
预期成绩:
hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
Run Code Online (Sandbox Code Playgroud)
comment_re = re.compile(
r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE
)
def comment_replacer(match):
start,mid,end = match.group(1,2,3)
if mid is None:
# single line comment
return ''
elif start is not None or end is not None:
# multi line comment at start or end of a line
return ''
elif '\n' in mid:
# multi line comment with line break
return '\n'
else:
# multi line comment without line break
return ' '
def remove_comments(text):
return comment_re.sub(comment_replacer, text)
Run Code Online (Sandbox Code Playgroud)
(^)?只要使用MULTILINE-flag ,如果注释从一行的开头开始,则匹配.[^\S\n]将匹配除换行符之外的任何空白字符.如果评论从它自己的行开始,我们不希望匹配换行符./\*(.*?)\*/将匹配多行注释并捕获内容.懒惰匹配,所以我们不匹配两个或多个评论.DOTALL-flag使.匹配换行符.//[^\n]将匹配单行评论..由于DOTALL-flag 无法使用.($)?只要使用MULTILINE-flag ,如果注释在一行的末尾停止,则匹配.例子:
>>> s = ("qwe /* 123\n"
"456\n"
"789 */ asd /* 123 */ zxc\n"
"rty // fgh\n")
>>> print '"' + '"\n"'.join(
... remove_comments(s).splitlines()
... ) + '"'
"qwe"
"asd zxc"
"rty"
>>> comments_test = ("hello // comment\n"
... "line 2 /* a comment */\n"
... "line 3 /* a comment*/ /*comment*/\n"
... "line 4 /* a comment\n"
... "continuation of a comment*/ line 5\n"
... "/* comment */line 6\n"
... "line 7 /*********\n"
... "********************\n"
... "**************/\n"
... "line ?? /*********\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "**************/\n")
>>> print '"' + '"\n"'.join(
... remove_comments(comments_test).splitlines()
... ) + '"'
"hello"
"line 2"
"line 3 "
"line 4"
"line 5"
"line 6"
"line 7"
"line ??"
"line ??"
Run Code Online (Sandbox Code Playgroud)
编辑:
事实上你甚至不得不问这个问题,而且我们说的解决方案不是完全可读的:-)应该是一个很好的迹象,表明RE不是这个问题的真正答案.
从可读性的角度来看,您可以将其作为一个相对简单的解析器进行实际编码.
很多时候,人们试图使用RE来"聪明"(我并不是以贬低的方式),认为一条线是优雅的,但他们最终得到的是一个不可维护的角色泥沼.我宁愿拥有一个完全评论的20行解决方案,我可以在瞬间理解.