Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string between repeating characters

Tags:

java

regex

split

I want to take any given string and split it based on repeating characters.

As an example, if I were to input the string abcaaabbc, I would want to output an array of strings equal to: [abca, a, ab, bc]. Each time a character repeats, I want to start a new string.

Doing this with a loop is possible, of course, but I am wondering if I can achieve it using the String.split() method. If so - what would the RegEx be?

like image 969
Bohemian Avatar asked Dec 29 '12 06:12

Bohemian


1 Answers

Tokenize the input string where previous character(look-behind (?<=(.))) is same as next character(look-ahead (?=\\1)) and \1 captures (.).

    String str = "abcbabaaabbc";
    String regex = "(?<=(.))(?=\\1)";        
    System.out.println(Arrays.toString(str.split(regex)));
like image 189
Prince John Wesley Avatar answered Oct 02 '22 16:10

Prince John Wesley