Tutorial :Retrieve number from the string pattern using regular expression



Question:

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?


Solution:1

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)


Solution:2

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


Solution:3

This regular expression should do it:

\d+  


Solution:4

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"  


Solution:5

 # 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  


Solution:6

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »