舉例:
"aaav.*sddff+ss" -> "av.*sdf+s"
代碼:
//去重操作 String str = "aaav.*sddff+ss"; String regex = "(.)\\1+"; Matcher matcher = Pattern.compile(regex).matcher(str); String res = matcher.replaceAll("$1"); System.out.println(res);
主要用到正則表達式分組的概念。
\1 用於正則表達式內取值,取的是第一個分組匹配到的值。
$1 用於正則表達式外取值, 取的是第一個分組匹配到的值。常用於replace方法。