Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby grep多行字符串中的单行_Ruby_Grep - Fatal编程技术网

Ruby grep多行字符串中的单行

Ruby grep多行字符串中的单行,ruby,grep,Ruby,Grep,变量str包含多行字符串。我想从中挤出一句话。我想grep字符串行kernelrelease721,并将其分配给一个变量。有什么办法吗 irb(main):152:0> print str *************************** Component ******************** c:\temp\agent\bin\CAR.exe: 721, patch 618, changelist 1633822, NTAMD64, opt *****************

变量
str
包含多行字符串。我想从中挤出一句话。我想grep字符串行
kernelrelease721
,并将其分配给一个变量。有什么办法吗

irb(main):152:0> print str
*************************** Component ********************
c:\temp\agent\bin\CAR.exe: 721, patch 618, changelist 1633822, NTAMD64, opt
**********************************************************
--------------------
AGENT information
--------------------

kernel release                721

kernel make variant           721_REL

compiled on                   NT 6.1 7601 S x86 MS VC++ 14.00 for NTAMD64

compiled for                  64 BIT

compilation mode              Non-Unicode

compile time                  Mar 21 2016 21:07:50

patch number                  12

latest change number          1659167


---------------------
supported environment
---------------------

operating system
Windows NT 5.0
Windows NT 5.1
Windows NT 5.2
Windows NT 6.0
Windows NT 6.1


哪个可能更有效

我假设您对该值感兴趣,即
721

kernel_release = str[/^kernel release\s+(\w+)$/, 1]
#=> "721"

正则表达式匹配一行,该行以
内核版本
开头,后跟空格,以一个或多个单词字符结尾。后者被捕获,第二个参数
1
引用该捕获组。

为什么要求使用
grep
?考虑在选择答案之前等待更长时间。不用着急。
string.each_line.grep /pattern/
kernel_release = str[/^kernel release\s+(\w+)$/, 1]
#=> "721"