【问题标题】:Best way to Remove the domain from url从 url 中删除域的最佳方法
【发布时间】:2019-01-23 23:28:54
【问题描述】:

我必须从中删除域的网址:http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es&profile=sportscenter_v1

您是否知道一种更好的方法来实现这一目标,而无需使用以下内容:

def example= decodeUrl.replace("http://www.espn.com", "")

谢谢

【问题讨论】:

    标签: groovy


    【解决方案1】:

    使用 java.net.URI 类。如果您从 url 字符串创建 URI,您将可以访问地址、行、路径、查询、方案、主机端口等的所有组件。 https://docs.oracle.com/javase/7/docs/api/java/net/URI.html

    URI uri = new URI("http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es&profile=sportscenter_v1")
    println uri.path +"?"+ uri.query
    

    【讨论】:

    • 虽然这段代码可以回答这个问题,但它缺乏解释。请考虑添加文字来解释它的作用,以及它为什么回答所提出的问题。
    【解决方案2】:

    如果您的域总是“.com” 那么你可以试试下面的

         def url = "http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es&profile=sportscenter_v1"
         /*The split function will spit the give string with a given sub string and store the splitted result in array of parts so here we are picking the second part having index 1*/
         def splitedUrl = url.split(".com")[1]
         println splitedUrl
    

    【讨论】:

      【解决方案3】:

      你可以这样写,所以域无关紧要。

      所以这里我们使用模式匹配

      def uri ="http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es&profile=sportscenter_v1"
      def parameters= uri=~ "https?://.*?/(.*)"
      log.info parameters[0][1]
      

      到目前为止,编写的模式也可以处理 http 和 https

      您可能必须使用 try catch,以防万一只有 www.espn.com 没有任何参数来处理这种情况

      要涵盖 url 的所有可能场景,您可以参考link

      尽管 Yeugeniuss 分享的答案是最合乎逻辑的,但这也是一种方法

      【讨论】:

        猜你喜欢
        • 2015-07-16
        • 2011-01-24
        • 1970-01-01
        • 2012-06-14
        • 1970-01-01
        • 2013-01-16
        • 2010-09-17
        • 2021-08-10
        • 1970-01-01
        相关资源
        最近更新 更多