简体   繁体   中英

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?

尝试使用先行式和后行式:

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

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"
"GENEINFO=AGRN:"[/(?<==).*(?=:)/]
# => "AGRN"

You want a lookbehind and lookahead.

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

// [["AGRN"]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM