简体   繁体   中英

Problem with Ruby Regular Expression

I have this HTML code, that's on a single line:

<h3 class='r'><a href="www.google.com">fkdsafjldsajl</a></h3><h3 class='r'><a href="www.google.com">fkdsafjldsajl</a></h3>

Here is the line-friendly version (that i can't use)

<h3 class='r'><a href="www.google.com">fkdsafjldsajl</a></h3>
<h3 class='r'><a href="www.google.com">fkdsafjldsajl</a></h3>

And i'm trying to extract just the URLs, with this REGEX

/<h3 class="r"><a href="(.*)">(.*)<\/a>/

And it returns

www.google.com">fkdsafjldsajl</a></h3><h3 class='r'><a href="www.google.com"

What can I do to stop it when find a " ?

The problem is that * is greedy. Put a question mark after it to make it ungreedy.

Working regex (tested on rubular )

href\=\"(.*?)\"

Sigh. Regex and HTML are such awkward bedfellows:

require 'nokogiri'

html = %q{<h3 class='r'><a href="www.google.com">fkdsafjldsajl</a></h3><h3 class='r'><a href="www.google.com">fkdsafjldsajl</a></h3>}
doc = Nokogiri::HTML(html)
puts doc.css('a').map{ |a| a['href'] }
# >> www.google.com
# >> www.google.com

This will find them, whether they are deeply nested or all on one line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM