2

Can anyone guide me on writing regularexp that I would use in my java code for extracting just the ip from http://10.22.14.152/something/api

expected result: 10.22.14.152

user3362080
  • 301
  • 1
  • 4
  • 10
  • 1
    This is an XY problem. The proper way to get the host from a URL is not with a regular expression, but with `new URI(string).getHost()`. – VGR May 03 '16 at 20:54

2 Answers2

5

use the structure of the URL to fashion very simple regular expression:

 http://(.*?)/
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
5

Just to show a different way to do this, (though sweaver2112's answer is much better)...

You know the format will be in the form of (http:)//(ipaddress)/(directory)/(directory)... You can split around the / and grab the 3 element in the array to get the IP...

String url = "http://10.22.14.152/something/api";
String[] splitUp = url.split("/");
String ipAddress = splitUp[2];
Rabbit Guy
  • 1,840
  • 3
  • 18
  • 28
  • Why would sweaver's answer be better I actually like yours more. RegEx's are resource-intensive. Often times, string operations such as split or substring are a better way to go - if you don't need the expressiveness of RegEx. – Bram Vanroy May 03 '16 at 19:41
  • @BramVanroy RegEx is resource intensive, yes, but for such a small issue, his is easier to read and the bottom line isn't noticeable to the end user. I think my solution helps moreso as you can see exactly what is happening, compared to using a RegEx, but I think in this case, RegEx actually is the better solution... It's an opinion, of course :) – Rabbit Guy May 03 '16 at 19:43
  • 2
    I finally used java.net.URL to extract the ip address https://docs.oracle.com/javase/7/docs/api/java/net/URL.html – user3362080 May 03 '16 at 20:00