Split string array in Java using regex

Charles Morin :

I'm trying to split this string :

aba(2)bb(52)gc(4)d(2)fe(14)f(6)g(8)h(4)5(6)

so it looks like this array :

[ a, b, a(2), b, b(52), g, c(4), d(2), f, e(14), f(6), g(8) ]

Here are the rules, it can accept letters a to g, it can be a letter alone but if there is parentheses following it, it has to include them and its content. The content of the parentheses must be a numeric value.

This is what I tried :

content = "aba(2)bb(52)gc(4)d(2)fe(14)f(6)g(8)h(4)5(6)";
        a = content.split("[a-g]|[a-g]\\([0-9]*\\)");
        for (String s:
             a) {
            System.out.println(s);
        }

And here's the output

(2)

(52)

(4) (2)

(14) (6) (8)h(4)5(6)

Thanks.

Wiktor Stribiżew :

It is easier to match these substrings:

String content = "aba(2)bb(52)gc(4)d(2)fe(14)f(6)g(8)h(4)5(6)";
Pattern pattern = Pattern.compile("[a-g](?:\\(\\d+\\))?");
List<String> res = new ArrayList<>();
Matcher matcher = pattern.matcher(content);
while (matcher.find()){
    res.add(matcher.group(0)); 
} 
System.out.println(res);

Output:

[a, b, a(2), b, b(52), g, c(4), d(2), f, e(14), f(6), g(8)]

See the Java demo and a regex demo.

Pattern details

  • [a-g] - a letter from a to g
  • (?:\(\d+\))? - an optional non-capturing group matching 1 or 0 occurrences of
    • \( - a ( char
    • \d+ - 1+ digits
    • \) - a ) char.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=82212&siteId=1