Fay Zan Fay Zan - 5 months ago 21
Java Question

Extracting certain text from URL in Android

Let's say I saved a URL of http://192.168.0.123:321. I just want to extract 192.168.0.123.I can do this by using this method

url.toString().substring(7,(url.length()-4));


But what if the saved URL is http://192.168.0.1:12 ?How do I automatically extract just the IP address?Because the method I just used would display
192.168.0.
instead

EDIT
I am using Java on Android Studio

EDIT 2
I used

str = url.toString();
ip = str.substring(str.indexOf('/')+1, str.lastIndexOf(':');


because the second one made me crash and I could not find ways to fix it

Answer

Edit! : For Android (Java) use the following code :

(new URL(urlToParse)).getAuthority();

or just the getAuthority() method for hostname:port

consult https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html


What language are you using ?

How about using String.split(':') or String.lastIndexOf(':') (and indexof '/') if they are available in your language of choice ?

You can also use regex - Regular Expressions but that might be an overkill for such a simple task. But it sure is more accurate/correct.

Also many languages provide URL parsing for you to extract the hostname/ip-address .

naive method :

str = url.toString();
ip = str.substring(str.indexOf('/')+1, str.lastIndexOf(':');

less naive method :

str = url.toString();
ip = str.split('/')[2].split(':')[0];

regex (only for ip-address based urls) :

/$https?:\/\/([0-9\.]*?)(:[0-9]*?)?/