grep single line from multiline string

2019-09-08 12:27发布

A variable str holds a multi line string. I want to grep a line from it. I want to grep the string line kernel release 721 and assign it to a variable. Is there any way to do so?

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

标签: ruby grep
2条回答
何必那么认真
2楼-- · 2019-09-08 12:58

I assume that you are interested in the value, i.e. 721:

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

The regular expression matches a line that starts with kernel release, followed by whitespace and ends with one or more word characters. The latter are captured and the second argument 1 refers to that capture group.

查看更多
虎瘦雄心在
3楼-- · 2019-09-08 13:01
string.lines.grep /pattern/

or

string.each_line.grep /pattern/

which might be more efficient

查看更多
登录 后发表回答