检查文件中的模式

时间:2014-08-07 17:03:48

标签: ruby regex

我想检查文件中的图案,如果找不到图案,则打印警告或其他内容。该文件大约有100行。

这是我试过的代码。

file = file.open("file_tobe_checked", "r")
while (line=file.get)
  if (line =~ /Copyright \W+ \d\d\d\d/).nil?  # the pattern I want to check
    puts "Copyright is missing or written in a wrong format"
  end
end
file.close 

此代码检查版权模式并为每一行打印"Copyright is missing.."。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

使用file.read将文件存储到单个字符串中。

file = File.open("file_tobe_checked", "r")
contents = file.read

if (contents =~ /Copyright \W+ \d\d\d\d/).nil?  # the pattern I want to check
    puts "Copyright is missing or written in a wrong format"
end

file.close 

有关详细信息,请参阅IO.read。 http://www.ruby-doc.org/core-2.0/IO.html#method-c-read

警告:如果您知道自己的文件相当小,并且知道版权将接近最终,那么效果会很好。

答案 1 :(得分:0)

你很亲密:

found_copyright = false

file = file.open("file_tobe_checked", "r")  #opened the file I wanted to check
while (line=file.get && !found_copyright)
  found_copyright = found_copyright || (line =~ /Copyright \W+ \d\d\d\d/)
end
file.close 

unless found_copyright
  puts "Copyright is missing or written in a wrong format"
end