user44552
user44552

Reputation: 163

extract with regex, one liner in ruby

I would like to extract the word after "=". For "GENEINFO=AGRN:" in a document, I can use the regex /GENEINFO=(.*?):/ to extract the required. However the value I wanted to returned is just "AGRN". Is there a one-liner that I can use for this task?

Upvotes: 0

Views: 82

Answers (4)

sawa
sawa

Reputation: 168071

"GENEINFO=AGRN:"[/(?<==).*(?=:)/]
# => "AGRN"

Upvotes: 1

Justin Ko
Justin Ko

Reputation: 46826

You could also use match:

'GENEINFO=AGRN:'.match(/GENEINFO=(.*?):/)[1]
#=> "AGRN"

Which could also be written using the String#[] method:

'GENEINFO=AGRN:'[/GENEINFO=(.*?):/, 1]
#=> "AGRN"

Upvotes: 2

KChaloux
KChaloux

Reputation: 4028

You want a lookbehind and lookahead.

pattern = /(?<=GENEINFO=)(.*?)(?=:)/
value = "GENEINFO=AGRN:".scan(pattern)

// [["AGRN"]]

Upvotes: 0

tenub
tenub

Reputation: 3446

Try using a lookbehind and a lookahead:

/(?<=GENEINFO=).*?(?=:)/

Upvotes: 3

Related Questions