我正在尝试从字符串中提取网址,它们没有标准化,因此有些位于 href 标签内,其他则位于自己的标签内。
此外,我需要它们按类型排序,例如以下字符串:
var txt1: String = "Some text! <a href="http://www.google.com/test.mp3">MP3</a>"
var txt2: String = "Some text! <a href="http://www.google.com/test.jpg">IMG</a>"
var txt3: String = "Some more! <a href="http://www.google.com/">Link!</a>"
所以这些字符串都是串联的并包含 3 个 url,我正在寻找类似的内容:
var result: List = List(
"mp3" -> List("http://www.google.com/test.mp3"),
"img" -> List("http://www.google.com/test.jpg"),
"url" -> List("http://www.google.com/")
)
我研究过正则表达式,但只在没有定义类型的情况下提取 href,而且这也不会在标签之外检索自己的 URL
val hrefRegex = new Regex("""\<a.*?href=\"(http:.*?)\".*?\>.*?\</a>""");
val hrefs:List[String]= hrefRegex.findAllIn(txt1.mkString).toList;
非常感谢任何帮助,提前致谢:)
最佳答案
假设val txt = txt1 + txt2 + txt3
,您可以将文本作为字符串包装到 xml 元素中,然后将其解析为 XML,并使用 xml 标准库提取 anchor 。
// can do other cleanup if necessary here such as changing "link!"
def normalize(t: String) = t.toLowerCase()
val txtAsXML = xml.XML.loadString("<root>" + txt + "</root>")
val anchors = txtAsXML \\ "a"
// returns scala.xml.NodeSeq containing the <a> tags
然后您只需要进行后期处理,直到数据按照您想要的方式组织:
val tuples = anchors.map(a => normalize(a.text) -> a.attributes("href").toString)
// Seq[String, String] containing elements
// like "mp3" -> http://www.google.com/test.mp3
val byTypes = tuples.groupBy(_._1).mapValues(seq => seq.map(_._2))
// here grouped by types:
// Map(img -> List(http://www.google.com/test.jpg),
// link! -> List(http://www.google.com/),
// mp3 -> List(http://www.google.com/test.mp3))
关于regex - 从带有类型的字符串中提取 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7767805/