Retrieve number from the string pattern using regular expression

11,382

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

 # 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 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"
Share:
11,382
MOZILLA
Author by

MOZILLA

Software Developer

Updated on June 07, 2022

Comments

  • MOZILLA
    MOZILLA almost 2 years

    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?