How to split a line if another character occurs?

I have a line as shown below:

String str = "77755529";

I want to break this line if a different number happens. The result should look like this after splitting:

str1 = "777";
str2 = "555";
str3 = "2";
str4 = "9";

I tried it with a section, but could not do it.

+4
source share
2 answers

Try the following:

String   str = "77755529";
String[] res = str.split("(?<=(.))(?!\\1)");

IDEONE SAMPLE

+8
source

You can perform the mapping.

List<String> lst = new ArrayList<String>();
Matcher m = Pattern.compile("(\\d)\\1+|\\d+").matcher(s);
while(m.find()) {
   lst.add(m.group());
}
System.out.println(lst);
+2
source

Source: https://habr.com/ru/post/1614395/


All Articles