记录一下Java常用的但没有工具包直接使用的工具类,持续更新中欢迎讨论。
对于某些字符串例如身份证、手机电话等需要脱敏展示,下面介绍4种方式。
@Test void test() { String testStr = "154565465654661"; String STAR_STR = "*"; int desensitiseLength = 6; // 1.利用StringBuilder的replace long start = System.nanoTime(); if (testStr.length() > desensitiseLength) { int midLength = testStr.length() / 2; StringBuilder sb = new StringBuilder(testStr); sb.replace(midLength - desensitiseLength / 2, midLength + desensitiseLength / 2, String.join("", Collections.nCopies(desensitiseLength, STAR_STR))); log.info("修改后的字符串:{},耗时:{} ns", sb.toString(), System.nanoTime() - start); } // 2.利用工具类 StringUtils String testStr2 = "154565465654661"; if (testStr2.length() > desensitiseLength) { int startIndex = (testStr2.length() - desensitiseLength) / 2 + 1; testStr2 = StringUtils.left(testStr2, startIndex). concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(testStr2, startIndex), StringUtils.length(testStr2), "*"), "******")); log.info("修改后的字符串:{},耗时:{} ns", testStr2, System.nanoTime() - start); } // 3.利用正则 long start3 = System.nanoTime(); String testStr3 = "154565465654661"; if (testStr3.length() > desensitiseLength) { int startIndex = (testStr2.length() - desensitiseLength) / 2; int endIndex = testStr3.length() - startIndex - desensitiseLength; testStr3 = testStr3.replaceAll("(\\w{" + startIndex + "})(\\w+)(\\w{" + endIndex + "})", "$1******$2"); log.info("修改后的字符串:{},耗时:{} ns", testStr3, System.nanoTime() - start3); } // 4.直接用subString方法 long start4 = System.nanoTime(); String testStr4 = "154565465654661"; if (testStr4.length() > desensitiseLength) { int startIndex = (testStr2.length() - desensitiseLength) / 2; int endIndex = (testStr2.length() + desensitiseLength) / 2; testStr4 = testStr4.substring(0, startIndex) + "******" + testStr4.substring(endIndex); log.info("修改后的字符串:{},耗时:{} ns", testStr4, System.nanoTime() - start4); } }
结果如下,可以看出按照耗时和性能比较,推荐使用第四种方式,方便快捷
修改后的字符串:1545******54661,耗时:316500 ns 修改后的字符串:15456****54661,耗时:5414600 ns 修改后的字符串:1545******654656,耗时:231200 ns 修改后的字符串:1545******54661,耗时:37700 ns