You can do that with split()
and some regex-magic:
System.out.println( Arrays.toString( "3332255766122".split( "(?<=(.))(?!\\1)" ) ));
Output:
[333, 22, 55, 7, 66, 1, 22]
Regex breakdown:
(?<=x)
is a positive zero-width look-behind, so it will match the position right after the match for subexpressionx
(.)
as epxression forx
above is a capturing group that matches any character and captures it for the next step. In combination with the part above, i.e.(?<=(.))
this means: “match any position after a character and capture that character into a group”(?!x)
is a negative look-ahead which matches any position that is not followed by a match of subexpressionx
.\1
is a back-reference to the match of the first capturing group ((.)
in this case), so in combination with the part above, i.e.(?!\1)
, this matches any position that does not match the character before
In words the expression would mean: “match any position after any character that is not followed by the same character”.
6
solved Java String.split() without specific symbol [closed]