24

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".

Bohemian
  • 412,405
  • 93
  • 575
  • 722

1 Answers1

32

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.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • in `.net` character within the group i.e `(.)` is also included in the result..i wonder why it's not the case with `java` – Anirudha Nov 28 '12 at 08:17
  • @Some1.Kill.The.DJ: I guess there are some difference here and there between different languages. I have no idea to how achieve the same effect in .NET (or Ruby, since it also include capturing group in the result of split). – nhahtdh Nov 28 '12 at 13:05