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