Best way to Remove the domain from url

最后都变了- 提交于 2020-03-04 06:53:28

问题


I have to remove the domain's url from this: http://www.espn.com/watch/?gameId=1234&league=nfl&lang=es&profile=sportscenter_v1

Do you know a better way to achieve that without using things like:

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

Thanks


回答1:


Use java.net.URI class. If you create URI from url String, you will have access to all components of the address, line, path, query, scheme, host port etc. 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:


If your domain if always ".com" then you could try the following

     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:


You can write this so the domain does not matter.

So here we are using pattern matching

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]

As of now the pattern that is written it can take care for http and https as well

You may have to use try catch so in case only www.espn.com comes without any parameter to handle that situation

To cover all possible scenarios for url you may refer this link

Even though the answered shared by Yeugeniuss is the most logical but this is also one of the way to do it



来源:https://stackoverflow.com/questions/51886613/best-way-to-remove-the-domain-from-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!