gpt4 book ai didi

Java Regex - 掩码信用卡号

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:26:19 26 4
gpt4 key购买 nike

我有在字符串中屏蔽信用卡号的函数:

  public static String  replaceCreditCardNumber(String text){
final String MASKCARD = "$1<MASKED>$2";
final Pattern PATTERNCARD =
Pattern.compile("([0-9]{4})[0-9]{0,9}([0-9]{4})");
Matcher matcher = PATTERNCARD.matcher(text);
if (matcher.find()) {
return matcher.replaceAll(MASKCARD);
}
return text;

}

此函数在以下情况下工作正常:

    String text = "Aaaa bbbb aaa=1234567890123456 fdfdfd=aaa";
String expected = "Aaaa bbbb aaa=1234<MASKED>3456 fdfdfd=aaa";
assertEquals(expected,text);//OK

String text = "Aaaa bbbb aaa=\"1234567890123456\" fdfdfd=aaa";
String expected = "Aaaa bbbb aaa=\"1234<MASKED>3456\" fdfdfd=aaa";
assertEquals(expected,text);

但是以下情况失败

        String text = "Aaaa bbbb aaa=1gfg23fgfg4567890123456 fdfdfd=aaa";
String expected = "Aaaa bbbb aaa=1gfg23fgfg4567890123456 fdfdfd=aaa";
assertEquals(expected,text);

我得到了

        aaa=1gfg23fgfg4567[<MASKED>]3456

我的正则表达式中缺少什么?

最佳答案

您应该使用单词边界来确保避免匹配不需要的输入:

final Pattern PATTERNCARD = 
Pattern.compile("\\b([0-9]{4})[0-9]{0,9}([0-9]{4})\\b");

Working Demo

关于Java Regex - 掩码信用卡号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24238240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com