I need a regex pattern, which can mask alternative 2 chars in a string in java.. But the input string we cannot predict. For Example
String pattern = "abcdefgh";
OutPut: "ab\*\*ef\*\*"
So the expression should be common one. Not specific for the above string
This should work for you :
public static void main(String[] args) {
String pattern = "abcdefghijklmnop";
System.out.println(pattern.replaceAll("(\\w{2})(\\w{2})", "$1**"));
}
O/P :
ab**ef**ij**mn**
replaceAll("(\\\\w{2})(\\\\w{2})", "$1**"))
==> Replaces 2 groups 2 chars each with "2 chars,**".
Note that if you have odd chars, the last char will not be masked. This should fix it == > System.out.println(pattern.replaceAll("(\\\\w{2})(\\\\w{2})", "$1**").replaceAll("(\\\\w{2})\\\\w$", "$1*"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.