Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string if different character occur?

Tags:

java

string

I have a string like below:

String str = "77755529";

I want to split this string if different number occur i.e result should be like below after splitting :

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

I tried it with split but could not make it.

like image 901
Jennifer Avatar asked Dec 24 '22 12:12

Jennifer


2 Answers

Try this:

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

IDEONE SAMPLE

like image 70
Rahul Tripathi Avatar answered Jan 12 '23 03:01

Rahul Tripathi


You may do matching.

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);
like image 27
Avinash Raj Avatar answered Jan 12 '23 03:01

Avinash Raj