将内容与正则表达式匹配在文件中?

时间:2010-09-11 03:08:45

标签: ruby regex

我想查看文本是否已使用正则表达式存在于文件中。

# 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 个答案:

答案 0 :(得分:4)

如果您想支持变量而不是“Foo”和“Bar”,请使用:

/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]

将打印:

  
    

Foo住在Bar

  

答案 1 :(得分: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...')

答案 2 :(得分:2)

为什么要使用正则表达式来检查文字字符串?为什么不呢

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