최영훈
최영훈

Reputation: 31

Validating credit card number using regular expression

Credit Card Number format is : "nnnn nnnn nnnn nnnn"

I tested four strings below with this pattern, but the temp3 string unexpectedly returns true.

I don't know what's wrong. The regular expression I'm using should validate for four digits and one space exactly, but temp3 returns true despite not matching this pattern.

String temp1 = " adfs 1111 2222 3333 4444 fadad";  // outer test
String temp2 = "11 11 2222 3333 4444"; // inner test
String temp3 = "11111 2222 3333 4444"; // inner test
String temp4 = "1111 2a222 3333 4444"; // inner test

public String chkContainCardno(String inputstr) {

    Pattern p = Pattern.compile("[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}");
    Matcher m = p.matcher(inputstr);

    if (m.find()) {
        return m.group(0);
    } else {
        return ErrMsg.Does_Not_Contain_Card_No;
    }
}

[Test Result]

temp1 : adfs 1111 2222 3333 4444 fadad : true 1111 2222 3333 4444

temp2 : 11 11 2222 3333 4444 : false

temp3 : 11111 2222 3333 4444 : true 1111 2222 3333 4444 <-- I don't understand

temp4 : 1111 2a222 3333 4444 : false

Upvotes: 2

Views: 5992

Answers (2)

naro
naro

Reputation: 416

You can use this:

"(\\b\\d{4}\\s\\d{4}\\s\\d{4}\\s\\d{4}\\b)"

b - word boundaries

d - digit

Upvotes: 1

Nick
Nick

Reputation: 147216

The third test passes because you have no anchors around your pattern. You should add \b at either end i.e. "\\b[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}\\b" to force the match within word boundaries.

Upvotes: 3

Related Questions