Match a content with regexp in a file?
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 开发者_如何学PythonI match it with a regexp?
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
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...')
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"
精彩评论