使用此正则表达式(<a[^>]+>.+?<\\/a>)
我试图打印匹配的链接。使用斯卡拉匹配字符串内的hrefs
所以t1,t2,t3
应进行打印,但没有打印:
val str = "tester<a href=\"t1\">this is just test text<a href=\"t2\">\\r\\t\\s<a href=\"t3\">"
val re = "(<a[^>]+>.+?<\\/a>)".r
for (p <- re findAllIn str) p match {
case re(b) => print(b)
}
是正则表达式或如何在正则表达式实现不正确的?
更新:
使用公认的答案,这将下载所有有效的HREF从URL(以 'http' 开头),在这种情况下https://news.ycombinator.com/
:
import scala.io.Source
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import scala.collection.JavaConversions._
object Main extends App {
val hrefs = getHrefsFromPage("https://news.ycombinator.com/");
hrefs.foreach(e => println(e))
def getHrefsFromPage(url: String): List[(String, String)] = {
val doc = Jsoup.parse(Source.fromURL(url).mkString)
val aTags = doc.select("a").iterator.toList
val ts = (for (t <- aTags) yield (t.attr("href"), t.text))
val fts = ts.filter(f => f._1.trim.startsWith("http"))
return fts;
}
}
强制性SO链接:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454。阅读我的答案,看看解析html的替代方法。请不要用正则表达式解析html。 Html不是一种常规语言,所以正则表达式解析是不可靠的(英语语言是有限的,因此是规则的,所以我们在那里使用正则表达式)。 – faizan