-->

搜索文本文件,并显示字(红宝石)(Search for word in text file and

2019-09-26 13:42发布

我试图把用户的输入,通过一个文本文件搜索(不区分大小写的情况下),然后从文件显示的匹配,如果它(字的文件中的情况下)相匹配。 我不知道如何从文件中获取的话,这里是我的代码:

found = 0
words = [] 

puts "Please enter a word to add to text file"
input = gets.chomp

#Open text file in read mode 
File.open("filename", "r+") do |f|

  f.each do |line|
    if line.match(/\b#{input}\b/i)
      puts "#{input} was found in the file."   # <--- I want to show the matched word here
      #Set to 1 indicating word was found
      found = 1
    end
  end
end 

Answer 1:

所以,你想要做的是存储的结果match方法,你就可以得到实际的匹配词出来的是,IE。

if m = line.match( /\b#{input}\b/i )
  puts "#{m[0]} was found in the file."
  # ... etc.
end

更新

顺便说一句,你没有问-但我会用scan在这种情况下,让我的每行匹配的单词(如果有在同一行中多个匹配),像这样的数组:

if m = line.scan( /\b#{input}\b/i )
  puts "Matches found on line #{f.lineno}: #{m.join(', ')}"
  # ... etc.
end


Answer 2:

如果你不需要上报匹配的位置和文件不是过大,你可能只是这样做:

File.read("testfile").scan /\b#{input}\b/i

让我们试一下:

text = <<THE_END
Now is the time for all good people
to come to the aid of their local
grocers, because grocers are important
to our well-being.  One more thing.
Grocers sell ice cream, and boy do I
love ice cream.
THE_END

input = "grocers"
F_NAME = "text"
File.write(F_NAME, text)

File.read(F_NAME).scan /\b#{input}\b/i
  # => ["grocers", "grocers", "Grocers"]

File.read(F_NAME)返回一个字符串的整个文本文件。 scan /\b#{input}\b/i发送到该字符串。



文章来源: Search for word in text file and display (Ruby)