Need to mask only 14 digit Credit card number and pin using regular expressions
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Mask{
static String text="+919913623683,,,,1,2,,,4328798712363938,,,,5673,,7,8";
public static void main(String[] args){
System.out.println(replaceCreditCardNumber(text));
}
public static String replaceCreditCardNumber(String text){
String result = text.replaceAll("(\\d{16}(\\b([0-9]{4})[0-9]{0,9}([0-9]{4})\\b))", "$1--HIDDEN--,");
return result;
}
}
Input:
String text="+919913623683,,,,1,2,,,4328798712363938,,,,5673,,7,8";
output:
data="+919913623683,,,,1,2,,,************3988,,,,****,,7,8";
A simple & ugly example using chained replaceAll
invocations would look like (note that the order here is important):
String text="+919913623683,,,,1,2,,,4328798712363938,,,,5673,,7,8";
System.out.println(
text
// | not preceded by digit
// | | 4 digits
// | | | not followed by digit
// | | | | replace with literal ****
.replaceAll("(?<=\\D)\\d{4}(?=\\D)", "****")
// | 12 digits
// | | followed by 4 digits
// | | | replace with literal 12 *s
.replaceAll("\\d{12}(?=\\d{4})", "************")
);
Output
+919913623683,,,,1,2,,,************3938,,,,****,,7,8
As mentioned, you need the first replaceAll
invocation first. Otherwise you'd end up replacing the full 16-digit chunk with "*s", as it would match the condition for the 4-digit replaceAll
.
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.