Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Split not working as expected

I am trying to use a simple split to break up the following string: 00-00000

My expression is: ^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])

And my usage is:

String s = "00-00000";

String pattern = "^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])";

String[] parts = s.split(pattern);

If I play around with the Pattern and Matcher classes I can see that my pattern does match and the matcher tells me my groupCount is 7 which is correct. But when I try and split them I have no luck.

like image 876
LDAdams Avatar asked Jun 07 '10 05:06

LDAdams


2 Answers

String.split does not use capturing groups as its result. It finds whatever matches and uses that as the delimiter. So the resulting String[] are substrings in between what the regex matches. As it is the regex matches the whole string, and with the whole string as a delimiter there is nothing else left so it returns an empty array.

If you want to use regex capturing groups you will have to use Matcher.group(), String.split() will not do.

like image 128
krock Avatar answered Nov 12 '22 17:11

krock


for your example, you could simply do this:

String s = "00-00000";

String pattern = "-";

String[] parts = s.split(pattern);
like image 3
oezi Avatar answered Nov 12 '22 18:11

oezi