CanCeylan
CanCeylan

Reputation: 3010

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.

Upvotes: 1

Views: 313

Answers (3)

ichigolas
ichigolas

Reputation: 7735

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/

Upvotes: 3

valodzka
valodzka

Reputation: 5805

Way to get both at a time:

str = "<a href=\"javascript:launchRemote('99999','C')\">STACK OVER AND FLOW         </a>"
num, name = str.scan(/launchRemote\('(\d+)'[^>]+>\s*(.*?)\s*</).first
# => ["99999", "STACK OVER AND FLOW"]

Upvotes: 0

Hauleth
Hauleth

Reputation: 23586

This should work if you have only one link in string

str = %{<a href="javascript:launchRemote('99999','C')">STACK OVER AND FLOW             </a>}
num = str.match(/href=".*?'(\d*)'.*?/)[1].to_i
name = str.match(/>(.*?)</)[1].strip

Upvotes: 1

Related Questions