使用未注释的Java代码查找行的正则表达式是什么?

时间:2013-09-10 22:13:57

标签: ruby regex

我正在研究一个简单的Ruby程序,该程序应该包含Java文件中包含实际Java代码的文本行。即使行中有注释,该行也会被计算在内,因此基本上只有 注释的行才会被计算在内。

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

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

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

2 个答案:

答案 0 :(得分:1)

获取“代码行”的计数可能有点主观。自动生成的东西,比如进口和包装名称真的算吗?一个人通常不写。只有一个闭合花括号的线数?那条线路上没有任何执行逻辑。

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

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

这将省略:

  • 空行
  • 进口
  • 包名称为
  • 的行
  • 只有}}
  • 的行
  • 包含单行评论的行//
  • 打开多行注释((空白)/ *无论如何)
  • 延续多行评论((空白)*无论如何)

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

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

答案 1 :(得分: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