1

I have this kind of string: 16B66C116B or 222A3*C10B It's a number (with unknow digits) followed or by a letter ("A") or by a star and a letter ("*A"). This patter is repeated 3 times.

I want to split this string to have: [number,text,number,text,number,text]

[16, B, 66, C, 116, B] 

or

[16, B, 66, *C, 116, B]

I wrote this:

    String tmp = "16B66C116B";
    String tmp2 = "16B66*C116B";
    String pattern = "(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})";
    boolean q = tmp.matches(pattern);
    String a[] = tmp.split(pattern);

the pattern match right, but the splitting doesn't work.

(I'm open to improve my pattern string, I think that it could be write better).

Accollativo
  • 1,537
  • 4
  • 32
  • 56

2 Answers2

2

You are misunderstanding the functionality of split. Split will split the string on the occurence of the given regular expression, since your expression matches the whole string it returns an empty array.

What you want is to extract the single matching groups (the stuff in the brackets) from the match. To achieve this you have to use the Pattern and Matcher classes.

Here a code snippet which will print out all matches:

Pattern regex = Pattern.compile("(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})");
Matcher matcher = regex.matcher("16B66C116B");

while (matcher.find()) {
    for (int i = 1; i <= matcher.groupCount(); ++i) {
        System.out.println(matcher.group(i));
    }
}

Of course you can improve the regular expression (like another user suggested)

(\\d+)([A-Z]+)(\\d+)(\\*?[A-Z]+)(\\d+)([A-Z]+)
Sascha Wolf
  • 18,810
  • 4
  • 51
  • 73
  • The star can occurs before every letter and there is just one letter, so I think that the pattern is this: (\\d+)(\\*?[A-Z]) Thanks guys! I discovered that is the same to write: (\\d+)(\\*?[A-Z])(\\d+)(\\*?[A-Z])(\\d+)(\\*?[A-Z]) – Accollativo Jun 04 '14 at 09:21
2

Try with this pattern (\\d)+|(\\D)+ and use Matcher#find() to find the next subsequence of the input sequence that matches the pattern.

Add all of them in a List or finally convert it into array.

    String tmp = "16B66C116B";
    String tmp2 = "16B66*C116B";
    String pattern = "((\\d)+|(\\D)+)";

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(tmp);
    while (m.find()) {
        System.out.println(m.group());
    }
Braj
  • 46,415
  • 5
  • 60
  • 76