score:5

Accepted answer

Assuming val txt = txt1 + txt2 + txt3, you can wrap the text into an xml element as a string then parse it as XML and use the xml standard library to extract the anchors.

// 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

Then you just need to post process until you have the data organized like you want:

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))

Related Query

More Query from same tag