Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a content with regexp in a file?

Tags:

regex

ruby

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?

like image 551
never_had_a_name Avatar asked Sep 07 '25 17:09

never_had_a_name


1 Answers

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

like image 62
NullUserException Avatar answered Sep 09 '25 18:09

NullUserException