Split regex to extract Strings of contiguous characters
Asked Answered
C

1

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

Christychristye answered 28/11, 2012 at 1:46 Comment(0)
M
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.

Manchu answered 28/11, 2012 at 2:17 Comment(2)
in .net character within the group i.e (.) is also included in the result..i wonder why it's not the case with javaScholarship
@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).Manchu

© 2022 - 2024 — McMap. All rights reserved.