Николай Б Николай Б - 2 months ago 7
Java Question

How to split a string by every other separator

There's a string

String str = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";


How do I split it into strings like this
"ggg;ggg;"
"nnn;nnn;"
"aaa;aaa;"
"xxx;xxx;"
???????

Answer

Using Regex

    String input = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
    Pattern p = Pattern.compile("([a-z]{3});\\1;");
    Matcher m = p.matcher(input);
    while (m.find())
        // m.group(0) is the result
        System.out.println(m.group(0));

Will output

ggg;ggg;

nnn;nnn;

aaa;aaa;

xxx;xxx;