1

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.

3 Answers 3

3

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/

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for using Nokogiri, but, instead of doc.search('a').first use doc.at('a'). Instead of link.attribute('href').value use link['href']. Instead of href.scan(/'(\d+)'/).flatten use href[/(\d+)/, 1].
I agree with @the Tin Man, but just link['href'][/\d+/]
thank you very much for your answer. To understand more, can you please explain how does [/(\d+)/, 1] work ?
/(\d+)/ is a regular expression which matchs any sequence of digits. Using [/(\d+)/] on link['href'](a string), returns the part of the string that matchs that regex.
1

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

2 Comments

num returns nil :/ and for the name, how should I exclude > and < chars as well ?
Previously it was fast written, but now it is tested and working.
0

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"]

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.