Java Regex - 掩盖信用卡号

时间:2014-06-16 07:07:10

标签: java regex string

我有一个用字符串掩盖信用卡号的功能:

  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

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

3 个答案:

答案 0 :(得分:3)

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

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

Working Demo

答案 1 :(得分:1)

基于例子:

Pattern.compile("([0-9]{4})[0-9]{8}([0-9]{4})");

答案 2 :(得分:0)

我希望为您服务

我有以下课程:

$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";

如果返回值为“”(空),则替换信用卡号的字符串:表示字符串符合正则表达式中的任何组。

$(function() {
    $("#selectable").selectable();
});

$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
            var nthchild = ($(ui.selected).index() + 1);
            console.log(nthchild);
        }
    });
});

$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";