tags:

views:

35

answers:

3

I want to see if a text already is in a file using regexp.

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

I want to see if the text:

Hi my name is Foo
and I live in Bar

is in this file.

How can I match it with a regexp?

+1  A: 

Use this regular expression:

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

Example usage:

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

For something so simple a string search would also work.

File.open('file.txt').read().index('Hi my name...')
Mark Byers
+1  A: 

In case you want to support variables instead of "Foo" and "Bar", use:

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

As seen on rubular.

This also puts "Foo" and "Bar" (or whatever the string contained) in capture groups that you can later use.

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]

Will print:

Foo lives in Bar

NullUserException
+1  A: 

Why do you want to use a regexp for checking for a literal string? Why not just

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