我正在尝试编写一个正则表达式,将字符串的前4个字符替换为*
。
例如,对于输入123456
,预期输出为****56
。
如果输入长度小于4,则只返回*
。
例如,如果输入是123
,则返回值必须为***
。
这里有一个简单的解决方案,使用自 java-11 开始可用的 String#repeat(int)
。不需要使用正则表达式。
static String hideFirst(String string, int size) {
return size < string.length() ? // if string is longer than size
"*".repeat(size) + string.substring(size) : // ... replace the part
"*".repeat(string.length()); // ... or replace the whole
}
String s1 = hideFirst("123456789", 4); // ****56789
String s2 = hideFirst("12345", 4); // ****5
String s3 = hideFirst("1234", 4); // ****
String s4 = hideFirst("123", 4); // ***
String s5 = hideFirst("", 4); // (empty string)
null
(返回null
/抛出NPE/抛出自定义异常...)(.{0,4})(.*)
Pattern pattern = Pattern.compile("(.{0,4})(.*)");
Matcher matcher = pattern.matcher("123456");
if (matcher.matches()) {
String masked = matcher.group(1).replaceAll(".", "*");
String result = matcher.replaceFirst(masked + "$2");
System.out.println(result);
// 123456 -> ****56
// 123 -> ***
}
只需使用
String masked = string.replaceAll("(?<=^.{0,3}).", "*");
请查看正则表达式验证。
解释
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
.{0,3} any character except \n (between 0 and 3
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
. any character except \n
(?<!.{4}).
并替换为*
。 - bobble bubble