Search code examples
rubystringparsingstring-parsing

Extracting a part of a string in Ruby


I know this is an easy question, but I want to extract one part of a string with rails. I would do this like Java, by knowing the beginning and end character of the string and extract it, but I want to do this by ruby way, that's why I need your help.

My string is:

<a href="javascript:launchRemote('99999','C')">STACK OVER AND FLOW             </a>

And I want the numerical values between quotation marks => 99999 and the value of the link => STACK OVER AND FLOW

How should I parse this string in ruby ?

Thanks.


Solution

  • If you need to parse html:

    > require 'nokogiri'
    > str = %q[<a href="javascript:launchRemote('99999','C')">STACK OVER AND FLOW</a>]
    > doc = Nokogiri.parse(str)
    > link = doc.at('a')
    > link.text
    => "STACK OVER AND FLOW"
    > link['href'][/(\d+)/, 1]
    => "99999"
    

    http://nokogiri.org/