我是 rails 新手,目前我正在使用 ruby 处理 php、javascript/coffeescript 存储库的代码统计,我需要获取 php 和 javascript 和 coffeescript 的编码行和注释行(单行和多行注释)使用正则表达式的文件。任何人都可以帮助解决这个问题,在此先感谢
问问题
172 次
1 回答
1
这是我的男人:
f = File.open("test.php")
loc = 0
comments = 0
while line = f.gets
if commented ||= line.match(/^\/\*/)
commented = nil if line.match(/\*\/$/)
comments += 1
elsif line.match(/^\s*\/\//)
comments += 1
else
loc +=1 unless line.match(/^\s*\n/)
end
end
puts loc
puts comments
这适用于:
//line comments
/* inline block comments */
/* multi
line
comments */
这个怎么运作:
- 你打开文件
- 将计数器初始化为 0
- 使用gets遍历每一行并将其分配给行变量
- 如果该行与块注释的开头匹配,则设置注释变量
- 将 1 添加到评论变量
- 如果设置了commented,则搜索comment的结尾,如果找到则将commented设置为nil
- 否则,如果未打开评论块并且找到“//”,则在评论中添加 1
- 否则将 1 添加到 loc 除非它是“空”行
于 2012-12-20T01:54:49.060 回答