4

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?

NullUserException
  • 83,810
  • 28
  • 209
  • 234
never_had_a_name
  • 90,630
  • 105
  • 267
  • 383

4 Answers4

7

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
  • 83,810
  • 28
  • 209
  • 234
4

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
  • 811,555
  • 193
  • 1,581
  • 1,452
3

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
  • 2,103
  • 14
  • 9
0

Answer with automatic file closing. Can be used to get the first matching regex in the file:

found = File.read('file.txt')[/Hi my name is Foo\nand I live in Bar/]
rtrrtr
  • 563
  • 5
  • 7