开发者

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

Please first look at this exampl开发者_运维知识库e 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜