针对 URL 的 Scala 模式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7586605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala pattern matching against URLs
提问by Eric Hauser
Is there a Scala library/example that will parse a URL/URI into a case class structure for pattern matching?
是否有 Scala 库/示例可以将 URL/URI 解析为案例类结构以进行模式匹配?
回答by Alex Cruise
Here's an extractor that will get some parts out of a URL for you:
这是一个提取器,可以为您从 URL 中提取某些部分:
object UrlyBurd {
def unapply(in: java.net.URL) = Some((
in.getProtocol,
in.getHost,
in.getPort,
in.getPath
))
}
val u = new java.net.URL("http://www.google.com/")
u match {
case UrlyBurd(protocol, host, port, path) =>
protocol +
"://" + host +
(if (port == -1) "" else ":" + port) +
path
}
回答by Philippe
I would suggest to use the facility provided by extractors for regular expressions.
For instance:
例如:
val URL = """(http|ftp)://(.*)\.([a-z]+)""".r
def splitURL(url : String) = url match {
case URL(protocol, domain, tld) => println((protocol, domain, tld))
}
splitURL("http://www.google.com") // prints (http,www.google,com)
Some explanations:
一些解释:
- The
.rmethod on strings (actually, onStringLikes) turns them into an instance ofRegex. Regexes define anunapplySeqmethod, which allows them to be used as extractorsin pattern-matching (note that you have to give them a name that starts with a capital letter for this to work).- The values that are going to be passed into the binders you use in the pattern are defined by the groups
(...)in the regular expression.
.r字符串上的方法(实际上是StringLikes上的)将它们变成 的实例Regex。Regexes 定义了一个unapplySeq方法,允许它们在模式匹配中用作提取器(请注意,您必须给它们一个以大写字母开头的名称才能工作)。- 将要传递到您在模式中使用的活页夹中的值由
(...)正则表达式中的组定义。
回答by JaimeJorge
You can use java's URLwhich can parse an URL for its different components and is completely Scala compatible.
您可以使用java 的 URL,它可以解析不同组件的 URL,并且完全兼容 Scala。
回答by theon
The following library can help you parse URIs into an instance of a case class. (Disclaimer: it is my own library) https://github.com/theon/scala-uri
以下库可以帮助您将 URI 解析为案例类的实例。(免责声明:这是我自己的图书馆) https://github.com/theon/scala-uri
You parse like so:
你这样解析:
import com.github.theon.uri.Uri._
val uri:Uri = "http://example.com?one=1&two=2"
It provides a DSL for building URLs with query strings:
它提供了一个 DSL,用于使用查询字符串构建 URL:
val uri = "http://example.com" ? ("one" -> 1) & ("two" -> 2)

