Java separation with specific patern

String abc ="abc_123,low,101.111.111.111,100.254.132.156,abc,1";
String[] ab = abc.split("(\\d+),[a-z]");
System.out.println(ab[0]);

Expected Result:

abc_123
low
101.111.111.111,100.254.132.156
abc
1

The problem is that I cannot find the matching regular expression for this pattern.

+4
source share
4 answers

I suggest not solving all problems with one regex.

Your starting line seems to contain values ​​separated by a "," character. Therefore, divide these values ​​by ",".

Then repeat the output of this process; and “join” those items that are IP addresses (which seems to be what you are looking for).

And just for the sake of it: keep in mind that IP addresses are actually quite complex; template can be found here

+7
source
String[] ab = abc.split(",");
System.out.println(ab[0]);
System.out.println(ab[1]);
int i = 2;
while(ab[i].matches("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")) {
    if(i > 2) System.out.print(",");
    System.out.print(ab[i++]);
}
System.out.println();
System.out.println(ab[i++]);
System.out.println(ab[i++]);
+1

You can use lookahead and lookbehind to check if 3 digits and .in the right place precede or follow ,:

String[] ab = abc.split("(?<!\\.\\d{3}),|,(?!\\d{3}\\.)");
+1
source

first divide them into an array by ,, and then apply a regular expression to check if it is in the desired formate or not. If yes, indicate all that are shared,

String abc ="abc_123,low,101.111.111.111,100.254.132.156,abc,1";//or something else.
String[] split = abc.split(",");
String concat="";
for(String data:split){

boolean matched=data.matches("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
if(matched){
concat=concat+","+data;
}else{
System.out.println(data);
}
}
if(concat.length()>0)
System.out.println(concat.substring(1));
}
+1
source

All Articles