[英]replace String with another in java using regular Expression
In Java, I have to wrap a string value to another using RegEx and function replace.在 Java 中,我必须使用 RegEx 和 function 替换将字符串值包装到另一个值。
Example #1: What will replace " 123C5
" (5 characters) with " *****
"?示例 #1:什么将“
123C5
”(5 个字符)替换为“ *****
”?
Example #2: What will replace " 12354CF5214
" (11 characters) with " *******5214
"?示例#2:什么将“
12354CF5214
”(11 个字符)替换为“ *******5214
”? replace only the first 7 characters仅替换前 7 个字符
Currently, i am using this function but i need to optimize it:目前,我正在使用这个 function 但我需要优化它:
public String getMaskedValue(String value) {
String maskedRes = "";
if (value!=null && !value.isEmpty()) {
maskedRes = value.trim();
if (maskedRes.length() <= 5) {
return maskedRes.replaceAll(value, "$1*");
} else if (value.length() == 11) {
return maskedRes.replace(value.substring(0, 7), "$1*");
}
}
return maskedRes;
}
can anyone help me please?谁能帮帮我? thank you for advanced
谢谢你的先进
You may use a constrained-width lookbehind solution like您可以使用限制宽度的后视解决方案,例如
public static String getMaskedValue(String value) {
return value.replaceAll("(?<=^.{0,6}).", "*");
}
See the Java demo online .在线查看 Java 演示。
The (?<=^.{0,6}).
(?<=^.{0,6}).
pattern matches any char (but a line break char, with .
) that is preceded with 0 to 6 chars at the start of the string. pattern 匹配字符串开头前面有 0 到 6 个字符的任何字符(但换行符,带有
.
)。
A note on the use of lookbehinds in Java regexps:关于在 Java 正则表达式中使用lookbehinds的说明:
✽ Java accepts quantifiers within lookbehind, as long as the length of the matching strings falls within a pre-determined range.
✽ Java 接受后视中的量词,只要匹配字符串的长度在预定范围内。 For instance,
(?<=cats?)
is valid because it can only match strings of three or four characters.例如,
(?<=cats?)
是有效的,因为它只能匹配三个或四个字符的字符串。 Likewise,(?<=A{1,10})
is valid.同样,
(?<=A{1,10})
是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.