简体   繁体   English

在Java中屏蔽来自String的信用卡和密码

[英]Mask credit card and pin from String in java

Need to mask only 14 digit Credit card number and pin using regular expressions 仅需使用正则表达式屏蔽14位信用卡号和密码

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): 一个使用链接的replaceAll调用的简单且难看的示例如下所示(请注意,这里的顺序很重要):

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. 如前所述,您需要首先执行replaceAll调用。 Otherwise you'd end up replacing the full 16-digit chunk with "*s", as it would match the condition for the 4-digit replaceAll . 否则,您最终将用“ * s”替换完整的16位数字块,因为它将与4位replaceAll的条件匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM