tags:

views:

284

answers:

5

I have a string "Search result:16143 Results found", and I need to retrieve 16143 out of it.

I am coding in ruby and I know this would be clean to get it using RegEx (as oppose to splitting string based on delimiters)

How would I retrieve the number from this string in ruby?

+1  A: 

This regular expression should do it:

\d+
Spire
+2  A: 

I'm not sure on the syntax in Ruby, but the regular expression would be "(\d+)" meaning a string of digits of size 1 or more. You can try it out here: http://www.rubular.com/

Updated: I believe the syntax is /(\d+)/.match(your_string)

Brehtt
note that putting the \d+ in brackets actually captures the value, rather than just returning true or false in relation to the match
Brehtt
Don't forget to convert it to an integer (Neither Integer(foo) nor foo.to_i is perfect, but I'd suggest to_i if you *know* that it is a number).
Andrew Grimm
+1  A: 

For a non regular-expression approach:

irb(main):001:0> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
irb(main):002:0> foo[foo.rindex(':')+1..foo.rindex(' Results')-1]
=> "16143"
Gdeglin
+1  A: 
 # check that the string you have matches a regular expression
 if foo =~ /Search result:(\d+) Results found/
   # the first parenthesized term is put in $1
   num_str = $1
   puts "I found #{num_str}!"
   # if you want to use the match as an integer, remember to use #to_i first
   puts "One more would be #{num_str.to_i + 1}!"
 end
rampion
+2  A: 
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143