-1

is there a smart way (maybe with java8 streams) to extract the first ipAddress in a string with a format similar to that one:

some string, 151.0.247.187, 54.239.167.92, 52.49.172.244

Thanks

TheOni
  • 810
  • 9
  • 26
  • 2
    Split on comma, take the first? – Thorbjørn Ravn Andersen Oct 14 '16 at 10:31
  • the first token could be a generic string or an IP, I could receive something like "**some string, 151.0.247.187, 54.239.167.92, 52.49.172.244**" or "**151.0.247.187, 54.239.167.92, 52.49.172.244**" and in both case I need to extract **151.0.247.187** – TheOni Oct 14 '16 at 10:35
  • Try `str.replaceFirst(".*?(\\d+(\\.\\d+){3}).*", "$1")`. –  Oct 14 '16 at 10:37
  • 2
    And for the record: if you want to avoid downvotes, you should post more than just requirements. The idea is that we help you with problems in **your** code; this is not a place where you come and then people write code for you. Well, at least most of the time that is. – GhostCat Oct 14 '16 at 10:43
  • Possible duplicate of [Why in Java 8 split sometimes removes empty strings at start of result array?](http://stackoverflow.com/questions/22718744/why-in-java-8-split-sometimes-removes-empty-strings-at-start-of-result-array) – Durgpal Singh Oct 14 '16 at 10:51
  • There is no smart way. Write it as clearly as you can. – Thorbjørn Ravn Andersen Oct 14 '16 at 10:51
  • Without a logical pattern for you String, the values need to be evaluated. Using a regex to check if this looks like a valid IP ( 4 or 6 ? ) – AxelH Oct 14 '16 at 10:58

1 Answers1

-1

I discourage using split because then you always will depend upon the index value so to me ,a better option is regex

String data="some string, 151.0.247.187, 54.239.167.92, 52.49.172.244";
 Pattern pattern=Pattern.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})");
Matcher matcher = pattern.matcher(data);  
        if (matcher.find()) {  
            System.out.println(matcher.group());  
        }  

output :

151.0.247.187

1.) look for the Ip pattern

2.) display the first group

Note : there are many IP patterns available online , you can pick any suitable one

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • String.split *does* use regex. Also, your string won’t compile, because `\.` is not a valid escape sequence in a string. Also, this will fail if the "some string" happens to contain an IP-address-like sequence of characters in it. – VGR Oct 14 '16 at 13:27
  • @VGR oops thanks for the typo , i was testing it online but don't worry i tested this in java too and i know i didn't cover all the cases but the assured input gave me the liberty and also said there are lot other to fit better and this regex was not the best, but appropriate in this case, about split , how the user will come to know which index array has the first IP (looping?), anyway that's why i left a note too plus i will try better next time ,thanks for the typo and advise – Pavneet_Singh Oct 14 '16 at 13:34