首页 > 代码库 > 去除字符串中连续重复的字符

去除字符串中连续重复的字符

目的:把字符串中连续重复的字符赐除掉。                                         

输入:序列:kkkhan888shioobo66

正确的返回结果应该是:hanshibo

思路解析                                                                              

1 使用JAVA正则表达式,匹配出连续相同的字符或数字。

2 查找出匹配出来的序列,并取出来放到list里面

3 对list进行排序。把重复的序列排在前面。(该步可省略)

4找出连续重复的子序列,并把这些连续重复的子序列用空(字字符串)替换。

5 返回输出。

code                                                                                   

public class Test  {      public static void main(String[] args)      {          String strings = matcher("kkkhan888shioobo66");          System.out.println(strings);      }        public static String matcher(String input)      {          //创建一个List           List<String> list = new ArrayList<String>();          //创建匹配的模式          Pattern pattern = Pattern.compile("(.)\\1*");          //匹配器          Matcher matcher = pattern.matcher(input);          //查找与该模式匹配的子序列。从"+kkkhan888shioobo66" 里面 查找出 与 此模式 "(.)\\1*"  相匹配的 子序列。如果存在,返回true,如果不存在,返回false.          while (matcher.find())          {              //返回匹配的子序列,并加入到list里面。              list.add(matcher.group());          }          System.out.println(list);          //对分好组的List,进行排序。根据指定比较器产生的顺序对指定列表进行排序。把重复的序列排在前面。          Collections.sort(list, new Comparator<String>()          {              public int compare(String o1, String o2)              {                  return o2.length() - o1.length();              }          });          //找到连续重复的字符,加入到数组中。          String[] strings = list.toArray(new String[0]);          //找出连续并且重复的子序列。并且把这些连续重复的子序列用空字符串替换。          for(int i=0 ;i<=strings.length-1;i++){              if(strings[i].length()>1){                  System.out.println(strings[i]);                  input=input.replace(strings[i],"");                  System.out.println(input);              }          }          System.out.println("最终结果:"+input);          //返回把连续重复的字符赐除掉的字符序列。          return input;      }  }

java连续多位相同字符判断的正则表达式                                            

([0-9])\1{5} 或 ([\d])\1{5} 连续相同的6位数字 如:333333
([0-9a-zA-Z])\1{5}   连续相同的6位数字或字母 如:222222 cccccc ZZZZZZ
([\d])\1{2}([a-z])\2{2} 连续相同3位数字后根连续相同的三位小写字母 如:222www
([\d])\1{2}([a-z])\2{2}|([a-z])\3{2}([\d])\4{2} 同上,但是能匹配数字+字母或字母+数字 如:222www 或 www222
自己可以扩展,要注意的就是 \1 \2代表位置,从左到右递增

我是天王盖地虎的分割线                                                             

 

 

参考:http://blog.csdn.net/atomcrazy/article/details/9087187