count = 0
file.each_line do |ln|
# Manage multiline and single line comments.
# Exclude single line if and only if there isn't code on that line
next if ln =~ %r{^\s*(//|/\*[^*]*\*/$|$)} or (ln =~ %r{/\*} .. ln =~ %r{\*/})
count += 1
end
这里只有一个问题,那有一个多线评论也行代码,例如:
someCall(); /* Start comment
this a comment
even this
*/ thisShouldBeCounted();
但是:
imCounted(); // Comment
meToo(); /* comment */
/* comment */ yesImCounted();
// i'm not
/* Nor
we
are
*/
编辑 以下版本是更麻烦一点,但正确计数所有情况。
count = 0
comment_start = false
file.each_line do |ln|
# Manage multiline and single line comments.
# Exclude single line if and only if there isn't code on that line
next if ln =~ %r{^\s*(//|/\*[^*]*\*/$|$)} or (ln =~ %r{^\s*/\*} .. ln =~ %r{\*/}) or (comment_start and not ln.include? '*/')
count += 1 unless comment_start and ln =~ %r{\*/\s*$}
comment_start = ln.include? '/*'
end
并非如此简单。 '/ *'注释可以跨越多行。 – kiheru
这很有道理。在这种情况下,如果我有两个单独的正则表达式,其中一个可以检查注释是否跨越多行并相应地读取其他行,它会起作用吗? – gtorien
有关多行注释,请参阅http://stackoverflow.com/q/462843/897024。 – Kapep