2

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
  • 81,190
  • 27
  • 202
  • 228
never_had_a_name
  • 85,690
  • 100
  • 264
  • 377

3 Answers3

5

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
  • 81,190
  • 27
  • 202
  • 228
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
  • 767,688
  • 176
  • 1,542
  • 1,434
2

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
  • 1,903
  • 13
  • 9