Remove doubled letter from a string using java

后端 未结 4 789
孤独总比滥情好
孤独总比滥情好 2021-01-18 20:06

I need to remove a doubled letter from a string using regex operations in java. Eg: PRINCEE -> PRINCE APPLE -> APLE

4条回答
  •  孤独总比滥情好
    2021-01-18 20:19

    If you want to replace just duplicate ("AA"->"A", "AAA" -> "AA") use

    public String undup(String str) {
      return str.replaceAll("(\\w)\\1", "$1");
    }
    

    To replace triplicates etc use: str.replaceAll("(\\w)\\1+", "$1");

    To replace only a single dupe is a long string (AAAA->AAA, AAA->AA) use: str.replaceAll("(\\w)(\\1+)", "$2");

提交回复
热议问题