3

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?

Chad Birch
  • 73,098
  • 23
  • 151
  • 149
MOZILLA
  • 5,862
  • 14
  • 53
  • 59
  • Are you confident that the number will be non-negative, will not contain any non-numeric numbers, and will not be in exponential notation? – Andrew Grimm Mar 29 '09 at 23:47

6 Answers6

14
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143
2

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)

LaserJesus
  • 8,230
  • 7
  • 47
  • 65
  • note that putting the \d+ in brackets actually captures the value, rather than just returning true or false in relation to the match – LaserJesus Mar 29 '09 at 06:04
  • 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 Mar 29 '09 at 23:44
1

This regular expression should do it:

\d+
Spire
  • 685
  • 6
  • 15
1

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
  • 12,432
  • 5
  • 49
  • 65
1
 # 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
  • 87,131
  • 49
  • 199
  • 315
0
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo.scan(/\d/).to_i
=> 16143
przbadu
  • 5,769
  • 5
  • 42
  • 67