clever_bassi
clever_bassi

Reputation: 2480

Get url from a string groovy

I am working with a grails app. I need to extract only part of the url up to .com (or gov, edu, mil, org, net, etc.) from a string.

For example:

Input: https://stackoverflow.com/questions?=34354#es4 Output: https://stackoverflow.com/

Input: https://code.google.com/p/crawler4j/issues/detail?id=174 Output: https://code.google.com/

Can anyone suggest how it can be done? Also, if it can be done, I need to change https to http in the resulting string. Please help. Thanks.

Edit: I apologize to all the downvoters that I did not include the thing that I tried. This is what i tried:

URL url = new URL(website);
String webUrl = url.getprotocol()+"://"+url.getAuthority()

But I got the following error: MissingPropertyException occurred when processing request: [POST] /mypackage/resource/crawl

Upvotes: 3

Views: 4022

Answers (3)

Nahush Farkande
Nahush Farkande

Reputation: 5646

You can try

​String text = 'http://stackoverflow.com/questions?=34354#es4'
def parts = text.split('.com')
return parts[0] + ".com"

This should solve your problem

Upvotes: 0

clever_bassi
clever_bassi

Reputation: 2480

I found the error in my code as well. I mistyped getProtocol as getprotocol and it evaded my observation again and again. It should have been:

URL url = new URL(website);
String webUrl = url.getProtocol()+"://"+url.getAuthority()

Thanks everyone for helping.

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

Something like this satisfies the 2 examples given:

def url = new URL('http://stackoverflow.com/questions?=34354#es4')
def result = 'http://' + url.host +'/'
assert result == 'http://stackoverflow.com/'

def url2 = new URL('https://code.google.com/p/crawler4j/issues/detail?id=174')
def result2 = 'http://' + url2.host +'/'
assert result2 == 'http://code.google.com/'

EDIT:

Of course you can abbreviate the concatenation with something like this:

def url = new URL('http://stackoverflow.com/questions?=34354#es4')
def result = "http://${url.host}/"
assert result == 'http://stackoverflow.com/'

def url2 = new URL('https://code.google.com/p/crawler4j/issues/detail?id=174')
def result2 = "http://${url2.host}/"
assert result2 == 'http://code.google.com/'

Upvotes: 3

Related Questions