Scala 中解析 URL 参数
一段时间以来,我一直在努力寻找一个简洁的实用函数,用于从 Scala 中的编码 URL 中解析出合理的参数。尽管进行了大量的阅读和阅读,尝试使用库工具我没有任何特别有用的东西。
这是我当前的解决方案,使用了几个匹配集。我对人们为此提供的一些反馈或其他解决方案感兴趣。
def EncodedUrlToParamMap(encodedURL:String): Map[String,String] = {
def toMap(l:List[String], acc: Map[String,String]): Map[String,String] = {
if (l.length<2) acc
else if (l.length==2) toMap( List.empty, acc + (l.head -> URLDecoder.decode(l.tail.head,"UTF-8")))
else toMap( l.drop(2), acc+(l.head->l(2)))
}
val paramPattern: Regex = "\\?([\\s\\S]*)$".r
val valuePattern: Regex = "[^?=&]*".r
paramPattern.findFirstIn( encodedURL ) match {
case Some(params) =>
val values: List[String] = valuePattern.findAllIn( params ).toList.filter(_.nonEmpty)
toMap(values, Map.empty)
case None =>
Map.empty
}
}
- paramPattern 转换“https://www.domain.com/page?key1=value1&key2=value2” --> "?key1=value1&key2=value2"
- valuePattern 分隔每个 key &价值
I've been struggling for a while to get a neat utility function for parsing sensible parameters out of encoded URLs in Scala. Despite a lot of reading & trying with library tools I haven't anything particularly usable.
This is my current solution, using a couple of matching sets. I'd be interested in some feedback or other solutions people have for doing this.
def EncodedUrlToParamMap(encodedURL:String): Map[String,String] = {
def toMap(l:List[String], acc: Map[String,String]): Map[String,String] = {
if (l.length<2) acc
else if (l.length==2) toMap( List.empty, acc + (l.head -> URLDecoder.decode(l.tail.head,"UTF-8")))
else toMap( l.drop(2), acc+(l.head->l(2)))
}
val paramPattern: Regex = "\\?([\\s\\S]*)quot;.r
val valuePattern: Regex = "[^?=&]*".r
paramPattern.findFirstIn( encodedURL ) match {
case Some(params) =>
val values: List[String] = valuePattern.findAllIn( params ).toList.filter(_.nonEmpty)
toMap(values, Map.empty)
case None =>
Map.empty
}
}
- paramPattern transforms "https//www.domain.com/page?key1=value1&key2=value2" --> "?key1=value1&key2=value2"
- valuePattern separates each key & value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想提取键/值,可以用更简单的方法来完成,但首先只需输入字符串作为 URI
If you just want to extract the key/value, you can do that in a easier way but first, just type your string as an URI
考虑使用内置此功能的类型,即
org.http4s.Uri
。但如果您需要使用字符串:Consider to use a type which has this functionality build in, i.e.
org.http4s.Uri
. But if you need to work with a String: