Scala 中解析 URL 参数

发布于 2025-01-11 12:50:02 字数 1012 浏览 0 评论 0原文

一段时间以来,我一直在努力寻找一个简洁的实用函数,用于从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

☆獨立☆ 2025-01-18 12:50:02

如果您只想提取键/值,可以用更简单的方法来完成,但首先只需输入字符串作为 URI

  def EncodedUrlToParamMap2(encodedURL: URI): Map[String,String] = {
    val map = encodedURL
      .getRawQuery          //Method from URI - you get the query string directly (after the ?)
      .split("&")           //Split on "&"
      .collect {
        case s"$key=$value" => key -> value //Since scala 2.13, you can do pattern matching with extraction 
                                            // The -> creates a tuple of 2 elements
                                            // You can add URLDecoder on v here
      }
      .toMap                    // Get the whole as a Map
    map
  }

  val uri = new URI("https//www.domain.com/page?key1=value1&key2=value2")
  EncodedUrlToParamMap2(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

  def EncodedUrlToParamMap2(encodedURL: URI): Map[String,String] = {
    val map = encodedURL
      .getRawQuery          //Method from URI - you get the query string directly (after the ?)
      .split("&")           //Split on "&"
      .collect {
        case s"$key=$value" => key -> value //Since scala 2.13, you can do pattern matching with extraction 
                                            // The -> creates a tuple of 2 elements
                                            // You can add URLDecoder on v here
      }
      .toMap                    // Get the whole as a Map
    map
  }

  val uri = new URI("https//www.domain.com/page?key1=value1&key2=value2")
  EncodedUrlToParamMap2(uri)
静谧 2025-01-18 12:50:02

考虑使用内置此功能的类型,即org.http4s.Uri。但如果您需要使用字符串:

def encodedUrlToParamMap(encodedURL: String): Map[String, String] =
  encodedURL.split('?').toList match {
    case _ :: params :: Nil => params.split("&").collect { case s"$key=$value" => key -> value }.toMap
    case _                  => Map.empty[String, String]
  }

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:

def encodedUrlToParamMap(encodedURL: String): Map[String, String] =
  encodedURL.split('?').toList match {
    case _ :: params :: Nil => params.split("&").collect { case s"$key=$value" => key -> value }.toMap
    case _                  => Map.empty[String, String]
  }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文