'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
Solution 1:[1]
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.
Solution 2:[2]
You can use this:
"(\\b\\d{4}\\s\\d{4}\\s\\d{4}\\s\\d{4}\\b)"
b - word boundaries
d - digit
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick |
| Solution 2 |
