2

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

PaulG
  • 13,871
  • 9
  • 56
  • 78
최영훈
  • 31
  • 1
  • 3
  • 1st and 3rd are the only input which matched the pattern to find 4 groups of 4 digit numbers – Pavneet_Singh Sep 22 '18 at 05:24
  • 2
    There is a actual algorithm to check if a credit card is a real credit card number or not, it is called the [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) – Scott Chamberlain Sep 22 '18 at 05:26

2 Answers2

3

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.

Nick
  • 138,499
  • 22
  • 57
  • 95
1

You can use this:

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

b - word boundaries

d - digit

naro
  • 416
  • 7
  • 16