4
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 Output:

abc_123
low
101.111.111.111,100.254.132.156
abc
1

The problem is i am not able to find appropriate regex for this pattern.

M A
  • 71,713
  • 13
  • 134
  • 174
Krish Krishna
  • 317
  • 3
  • 15

4 Answers4

7

I would suggest to not solve all problems with one regular expression.

It seems that your initial string contains values that are separated by ",". So split those values with ",".

Then iterate the output of that process; and "join" those elements that are IP addresses (as it seems that this is what you are looking for).

And just for the sake of it: keep in mind that IP addresses are actually pretty complicated; a pattern "to match em all" can be found here

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
1
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++]);
zborek
  • 81
  • 8
  • this is not always we have to concate `ab[2]` & `ab[3]` only this may be less or more.`String` can be like `abc_123,low,101.111.111.111,100.254.132.156,101.111.111.111,abc,1` –  May 26 '15 at 12:57
  • Was not specified... Then we can like above (edited) – zborek May 26 '15 at 13:09
1

You could use lookahead and lookbehind to check, if 3 digits and a . at the correct place are preceding or following the ,:

String[] ab = abc.split("(?<!\\.\\d{3}),|,(?!\\d{3}\\.)");
fabian
  • 80,457
  • 12
  • 86
  • 114
1

first split them into array by , ,then apply regex to check whether it is in desired formate or not.If yes then concate all these separated by,

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));
}