ruby 将文件中的内容与regexp匹配?

ttcibm8c  于 2023-08-04  发布在  Ruby
关注(0)|答案(4)|浏览(87)

我想看看一个文本是否已经在一个文件中使用regexp。

# file.txt
Hi my name is Foo
and I live in Bar
and I have three children.

字符串
我想看看文本是否:

Hi my name is Foo
and I live in Bar


都在这个文件里
如何将其与regexp匹配?

wfypjpf4

wfypjpf41#

如果你想支持变量而不是“Foo”和“Bar”,请用途:

/Hi my name is (\w+)\s*and I live in (\w+)/

字符串
rubular所示。
这也会将“Foo”和“Bar”(或包含的任何字符串)放入捕获组中,供以后使用。

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]


将打印:
Foo住在Bar

iqxoj9l9

iqxoj9l92#

使用此正则表达式:

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

字符串
示例用法:

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


对于如此简单的东西,字符串搜索也可以工作。

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

zujrkrfu

zujrkrfu3#

为什么要使用regexp来检查文字字符串?为什么不干脆

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

字符串

vwhgwdsa

vwhgwdsa4#

回答自动关闭文件。可用于获取文件中第一个匹配的正则表达式:

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

字符串

相关问题