如何检测scala中的url

时间:2013-05-23 11:36:02

标签: scala

您好,例如,有内容和网址的文件。我只想要网址的内容是scala中有任何探测器。请建议我任何想法。谢谢提前

3 个答案:

答案 0 :(得分:2)

对于此问题以及许多其他问题:您可以使用Java的解决方案。

How to detect the presence of URL in a string.

import java.net.URL; import util.Try

val text = "abc http://stackoverflow.com stackoverflow.com http blah-blah-blah"

text.split{"""\s+"""}.map{ s => Try { new URL(s) } }.flatMap{ _.toOption }
//Array[java.net.URL] = Array(http://stackoverflow.com)

答案 1 :(得分:0)

关于此主题,请阅读Extract URL from string。使用哪种编程语言并不重要,问题总是一样的。我在2011年遇到了同样的挑战,我采用了在接受的答案中发布的方式(据我记得稍作修改)。

答案 2 :(得分:0)

我不确定如果我理解正确,但您可以尝试自己编写。查看this帖子。在创建了正确的正则表达式后,您可能会这样做(代码假定网址与其他内容的行不同):

val URL = """(http|ftp)://(.*)\.([/a-z]+)""".r
def splitURL(url: String) = url match {
  case URL(protocol, domain, tld) => println((protocol, domain, tld))
  case _ => ; // skip
}

val f = new File("file.txt")
val lines = scala.io.Source.fromFile(f).getLines()

lines foreach (splitURL)

这只是一个提示。您可能需要为您的特定情况定制更多。

修改

您可能需要更高级的正则表达式。看看记者的回答