Combine content with regular expression in file?

I want to see if there is text 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 there is text:

Hi my name is Foo
and I live in Bar

located in this file.

How can I match it with regex?

+2
source share
3 answers

Use this regex:

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

Usage example:

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

For something so simple, string searching will work.

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

If 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 .

It also puts "Foo" and "Bar" (or any line contained) in capture groups, which you can subsequently 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]

It will be printed:

Foo lives in a bar

+4

Why do you want to use a regular expression to validate a literal string? Why not just

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

All Articles