我试图从用户那里获取输入,搜索文本文件(不区分大小写),然后显示匹配的文件(如果文件中的单词大小写)。我不知道如何从文件中获取单词,这是我的代码:
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
答案 0 :(得分:1)
所以,你要做的是存储match
方法的结果,然后你就可以得到实际匹配的单词,即
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
答案 1 :(得分:1)
如果您不需要报告匹配的位置且文件不是太大,您可以这样做:
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
被发送到该字符串。