3

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

rasilvap
  • 1,771
  • 3
  • 31
  • 70

3 Answers3

3

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
yeugeniuss
  • 180
  • 1
  • 7
  • 1
    While this code may answer the question, it lacks explanation. Please consider adding text to explain what it does, and why it answers the question posed. – Nelewout Aug 18 '18 at 09:18
0

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
Nitin Dhomse
  • 2,524
  • 1
  • 12
  • 24
0

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

Gaurav Khurana
  • 3,423
  • 2
  • 29
  • 38