javaregexsplitcontiguous

Split regex to extract Strings of contiguous characters


Is there a regex that would work with String.split() to break a String into contiguous characters - ie split where the next character is different to the previous character?

Here's the test case:

String regex = "your answer here";
String[] parts = "aaabbcddeee".split(regex);
System.out.println(Arrays.toString(parts));

Expected output:

[aaa, bb, c, dd, eee]

Although the test case has letters only as input, this is for clarity only; input characters may be any character.


Please do not provide "work-arounds" involving loops or other techniques.

The question is to find the right regex for the code as shown above - ie only using split() and no other methods calls. It is not a question about finding code that will "do the job".


Solution

  • It is totally possible to write the regex for splitting in one step:

    "(?<=(.))(?!\\1)"
    

    Since you want to split between every group of same characters, we just need to look for the boundary between 2 groups. I achieve this by using a positive look-behind just to grab the previous character, and use a negative look-ahead and back-reference to check that the next character is not the same character.

    As you can see, the regex is zero-width (only 2 look around assertions). No character is consumed by the regex.