2010-09-11 55 views
2

我想看看文本是否已經在文件中使用正則表達式。在文件中匹配正則表達式的內容?

# file.txt 
Hi my name is Foo 
and I live in Bar 
and I have three children. 

我想看看如果文本:

Hi my name is Foo 
and I live in Bar 

是在這個文件中。

如何將它與正則表達式匹配?

回答

3

使用正則表達式:

/Hi my name is Foo 
and I live in Bar/ 

用法示例:

File.open('file.txt').read() =~ /Hi my name is Foo 
and I live in Bar/ 

對於這麼簡單的東西一個字符串搜索也將工作。

File.open('file.txt').read().index('Hi my name...') 
+0

我相信'File.read('file.txt')=〜...'也可以工作,不會留下句柄打開。 – astorije 2016-09-26 16:31:09

3

如果你想支持的變量,而不是 「富」 與 「酒吧」,使用:

/Hi my name is (\w+)\s*and I live in (\w+)/ 

由於看到rubular

這也會將「Foo」和「Bar」(或任何包含的字符串)放入捕獲組中,以後可以使用。

str = IO.read('file1.txt')  
match = str.match(/Hi my name is (\w+)\s*and I live in (\w+)/) 

puts match[1] + ' lives in ' + match[2] 

會打印:

富住在酒吧

2

你爲什麼要使用正則表達式用於檢查一個字符串?爲什麼不只是

File.open('file.text').read().include? "Hi my name is Foo\nand I live in Bar"