regex problem

K

K. R.

hi @all

I would like to scan a string of html-tags. I need it to take out all
links (a-tags) in the string, but I become only the last one. What is
wrong? See the code below...

response = '<a href="hello1.html">test1</a> - <a
href="hello2.html">test2</a>'
response.scan(/<a.*href="(.*?)"/) do |line|
puts line
end

thanks for helping!
 
F

franco

the first kleene star might need to be non greedy? in other words stop
at the first href consumed, not the last.
/<a.*?href="(.*?)"/
 
F

franco

but what if href is not the first attribute of said:
Franco is right. You could fix it by doing "a.*?href". However, I
would change "a.*href" to "a\s+href" since you're looking for any
amount of whitespace after the "a" and before the "href".

response = '<a href="hello1.html">test1</a> - <a href="hello2.html">test2</a>'
response.scan(/<a\s+href="(.*?)"/s) do |line|
puts line
end
 
K

K. R.

response.scan(/<a.*href="(.*?)"/) do |line|
but what if href is not the first attribute of <a/>?

Regardless which order has the attributes, because you can have any
sequence (.*) between the <a tag and href.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top