从网址中删除域的最佳方法

时间:2018-08-16 23:33:56

标签: groovy

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

您知道不使用以下方法来实现此目标的更好方法吗?

def example = encodeUrl.replace(“ http://www.espn.com”,“”)

谢谢

3 个答案:

答案 0 :(得分:0)

如果您的域始终为“ .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

答案 1 :(得分:0)

使用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 :(得分:0)

您可以编写此代码,因此域无关紧要。

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

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的回答是最合乎逻辑的,但这也是做到这一点的方法之一