regex - Extract a word from a sentence in Ruby -


i have following string:

str = "xxx host:1233455 yyy zzz!" 

i want extract value after host: string.

is there optimal way in ruby using regexp, avoiding multiple loops? solution welcome.

if have numbers, use following regex:

(?<=host:)\d+ 

the lookbehind find numbers right after host:.

see ideone demo:

str = "xxx host:1233455 yyy zzz!" puts str.match(/(?<=host:)\d+/) 

note if want match alphanumerics , not punctuation, can replace \d+ \w+.

also, if have dots, or commas inside, can use

/(?<=host:)\d+(?:[.,]\d+)*/ 

it extract values 4,445 or 44.45.455.

update:

in case need more universal solution (especially if need use regex on platform look-behind not supported (as in javascript), use capture group approach:

str.match(/\bhost:(\d+)/).captures.first 

note \b makes sure find host: whole word, not localhost:. (\d+) capture group value can refer backreferences, or via .captures.first in ruby.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -