我想看看一个文本是否已经在一个文件中使用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匹配?
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
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...')
型
zujrkrfu3#
为什么要使用regexp来检查文字字符串?为什么不干脆
File.open('file.text').read().include? "Hi my name is Foo\nand I live in Bar"
字符串
vwhgwdsa4#
回答自动关闭文件。可用于获取文件中第一个匹配的正则表达式:
found = File.read('file.txt')[/Hi my name is Foo\nand I live in Bar/]
4条答案
按热度按时间wfypjpf41#
如果你想支持变量而不是“Foo”和“Bar”,请用途:
字符串
如rubular所示。
这也会将“Foo”和“Bar”(或包含的任何字符串)放入捕获组中,供以后使用。
型
将打印:
Foo住在Bar
iqxoj9l92#
使用此正则表达式:
字符串
示例用法:
型
对于如此简单的东西,字符串搜索也可以工作。
型
zujrkrfu3#
为什么要使用regexp来检查文字字符串?为什么不干脆
字符串
vwhgwdsa4#
回答自动关闭文件。可用于获取文件中第一个匹配的正则表达式:
字符串