Removing repeated characters in String

后端 未结 4 1626
半阙折子戏
半阙折子戏 2020-12-20 04:49

I am having strings like this \"aaaabbbccccaaffffddcfggghhhh\" and i want to remove repeated characters get a string like this \"abcadcfgh\".

A simplistic implementati

相关标签:
4条回答
  • 2020-12-20 05:44

    You can do this:

    "aaaabbbccccaaffffddcfggghhhh".replaceAll("(.)\\1+","$1");
    

    The regex uses backreference and capturing groups.

    The normal regex is (.)\1+ but you've to escape the backslash by another backslash in java.

    If you want number of repeated characters:

    String test = "aaaabbbccccaaffffddcfggghhhh";
    System.out.println(test.length() - test.replaceAll("(.)\\1+","$1").length());
    

    Demo

    0 讨论(0)
  • 2020-12-20 05:44

    With regex, you can replace (.)\1+ with the replacement string $1.

    0 讨论(0)
  • 2020-12-20 05:47

    You can use Java's String.replaceAll() method to simply do this with a regular expression.

    String s = "aaaabbbccccaaffffddcfggghhhh";
    System.out.println(s.replaceAll("(.)\\1{1,}", "$1")) //=> "abcadcfgh"
    

    Regular expression

    (               group and capture to \1:
     .              any character except \n
    )               end of \1
    \1{1,}          what was matched by capture \1 (at least 1 times)
    
    0 讨论(0)
  • 2020-12-20 05:48

    use this pattern /(.)(?=\1)/g and replace with nothing
    Demo

    0 讨论(0)
提交回复
热议问题