Jon Beach
Jon Beach

Reputation: 13

Regex expression to match the first digit of a string with 4.

I am working on a credit card validation Java program and I am stuck on how to format a regex expression properly to check if the CC number starts with 4. This is what I have:

if (cardNum.matches("^4\\d"))

Upvotes: 1

Views: 1245

Answers (3)

Hearen
Hearen

Reputation: 7828

Since you are matching the whole Credit Card number and you are using s.matches().

And as you can see matches is actually checking the whole string that is invoking the method:

Tells whether or not this string matches the given regular expression.

And also it mentions:

An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression: Pattern.matches(regex, str)

So the Pattern provides details about how the regex works.

\d => A digit: [0-9]

^ => The beginning of a line

X+ => X, one or more times

In your case, you need to ensure the regex pattern match the whole credit card number.

if (cardNum.matches("^4\\d+"));

If you need to specify the length range to eliminate invalid numbers:

X{n,m} => X, at least n but not more than m times

You need to specify it as:

if (cardNum.matches("^4\\d{16,19}"));

If you are checking lots of the numbers, you'd better turn to Pattern instead to avoid senseless pattern compiling overhead as:

private final static Pattern CREDIT_CARD_PATTERN = Pattern.compile("^4\\d+");
if (CREDIT_CARD_PATTERN.matcher(s).matches());  

When it contains hyphens or whitespaces, you can use the regex as:

  1. "^4\\d{3}-\\d{4}-\\d{4}-\\d{3}" to match 4485-7622-4840-4312;
  2. ^4\\d{3}\s*\\d{4}\\s*\\d{4}\\s*\\d{4} to match 4485762248404312 and 4485 7622 4840 4312;

Upvotes: 0

D. Tastet
D. Tastet

Reputation: 11

Right now, your regex will only match the string "4\d." If you wanted it to mean "4, and then 0 or more decimals", you should use the Kleene star operator "*" like so 4\d*

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

The String#matches function applies the pattern you specify to the entire string input. So the following might be what you have in mind:

if (cardNum.matches("^4\\d+")) {
    // then CC starts with 4, followed by more numbers
}

But note that the problem of creating regular expressions to validate various types of credit card numbers is an old one, and has already been solved. Have a look here for more information.

Upvotes: 1

Related Questions