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?

1
  • Are you confident that the number will be non-negative, will not contain any non-numeric numbers, and will not be in exponential notation? Commented Mar 29, 2009 at 23:47

6 Answers 6

14
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143
Sign up to request clarification or add additional context in comments.

1 Comment

This is the preferred way to extract from a string based on a regex pattern.
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)

2 Comments

note that putting the \d+ in brackets actually captures the value, rather than just returning true or false in relation to the match
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).
1

This regular expression should do it:

\d+

Comments

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"

Comments

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

Comments

0
> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo.scan(/\d/).to_i
=> 16143

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.