Search code examples
xmlparsingscalamarkuptextile

Scala how to turn "urls" in Strings into an Anchor tag XML node.


Please first look at this example below to understand what I am talking about.

The input is a string. XML(aka NodeSeq) will be the output.

input string example = "Hi this is an example url http://www.example.com"

output of string example = <div>Hi this is an example url <a href="http://www.example.com">http://www.example.com</a></div>

I am not looking to use an entire markup language because I only want the links to "work" when I print them out on my website.

I would appreciate any advice on how I should accomplish this.


Solution

  • Try this:

    val urlRegex = """(?i)\b(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]""".r
    
    def conv(s: String) = scala.xml.XML.loadString("<div>"+(urlRegex replaceAllIn (s, m => """<a href="%s">%s</a>""" format (m.matched, m.matched)))+"</div>")
    

    See this question about regex for URLs. The above example is just the simplest one there.