[英]Regular expression to replace first 4 characters
我正在尝试编写一个正则表达式,用*
s 替换字符串的前 4 个字符
例如,对于123456
输入,预期的 output 是****56
。
如果输入长度小于 4 则只返回*
s。
例如,如果输入是123
,则返回值必须是***
。
这是一个使用String#repeat(int)
的简单解决方案,从java-11开始可用。 不需要正则表达式。
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 / 抛出自定义异常......)您可以尝试下面的正则表达式来捕获前最多 4 个字符。
(.{0,4})(.*)
现在,您可以使用 Pattern、Matcher 和 String 类来达到您想要的效果。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.