1

我正在开发一个简单的 Ruby 程序,该程序应该计算包含实际 Java 代码的 Java 文件中的文本行数。该行即使有评论也会被计算在内,所以基本上只有评论的行不会被计算在内。

我正在考虑使用正则表达式来解决这个问题。我的程序将逐行迭代并将其与“正则表达式”进行比较,例如:

while line = file.gets
    if line =~ regex
        count+=1
    end
end

不过,我不确定要使用什么正则表达式格式。有任何想法吗?

4

2 回答 2

3

获取“代码行数”的数量可能有点主观。像导入和包名这样的自动生成的东西真的应该算吗?一个人通常不会写它。仅带有右花括号的行算吗?那条线上实际上没有任何执行逻辑。

我通常使用这个正则表达式来计算 Java 代码行数:

^(?![ \s]*\r?\n|import|package|[ \s]*}\r?\n|[ \s]*//|[ \s]*/\*|[ \s]*\*).*\r?\n

这将省略:

  • 空行
  • 进口
  • 带有包名的行
  • 只有 } 的行
  • 带有单行注释的行 //
  • 打开多行注释((空白)/* 随便)
  • 多行注释的继续((空白)* 随便)

它还将匹配任一\n\r\n换行符(因为您的源代码可能包含任一取决于您的操作系统)。

虽然并不完美,但它似乎非常接近匹配所有我认为的“合法”代码行。

于 2013-09-10T22:42:36.033 回答
0
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
于 2013-09-10T23:20:16.570 回答