Java Regex – Credit Card Number Validation

In this java regular expression tutorial, we will learn to use regex to validate credit card numbers. We will learn about number format and validations of credit card numbers from multiple providers such as VISA, Mastercard, Amex and Diners etc.

1. Valid Credit Card Numbers Formats

On an actual credit card, the digits of the embossed card number are usually placed into groups of four. That makes the card number easier for humans to read. Each of the credit card companies uses this number format.

We’ll exploit that difference of formats between each company to allow users to enter a number without specifying a company. The company can be determined from the number. The format for each company is:

  • Visa : 13 or 16 digits, starting with 4.
  • MasterCard : 16 digits, starting with 51 through 55.
  • Discover : 16 digits, starting with 6011 or 65.
  • American Express : 15 digits, starting with 34 or 37.
  • Diners Club : 14 digits, starting with 300 through 305, 36, or 38.
  • JCB : 15 digits, starting with 2131 or 1800, or 16 digits starting with 35.
Below given regex assumes that before performing the check for a valid number, we will search-and-replace all spaces and hyphens explicitly.

With spaces and hyphens stripped from the input, the next regular expression checks if the credit card number uses the format of any of the six major credit card companies. It uses named capture to detect which brand of credit card the customer has.

If you don’t need to determine which type the card is, you can remove the six capturing groups that surround the pattern for each card type, as they don’t serve any other purpose.

If you accept only certain brands of credit cards, you can delete the cards that you don’t accept from the regular expression. For example, when deleting JCB, make sure to delete the last remaining “|” in the regular expression as well. If you end up with “|” in your regular expression, it will accept the empty string as a valid card number as well.

Regex : ^(?:(?<visa>4[0-9]{12}(?:[0-9]{3})?)|

Read more about credit card number formats in this wiki page.

2. Credit card number validation example

public static void main(String[] args)
List<String> cards = new ArrayList<String>();

//Valid Credit Cards
cards.add("xxxx-xxxx-xxxx-xxxx");  //Masked to avoid any inconvenience unknowingly

//Invalid Credit Card
cards.add("xxxx-xxxx-xxxx-xxxx"); //Masked to avoid any inconvenience unknowingly

String regex = "^(?:(?<visa>4[0-9]{12}(?:[0-9]{3})?)|" +
		"(?<mastercard>5[1-5][0-9]{14})|" +
		"(?<discover>6(?:011|5[0-9]{2})[0-9]{12})|" +
		"(?<amex>3[47][0-9]{13})|" +
		"(?<diners>3(?:0[0-5]|[68][0-9])?[0-9]{11})|" +

Pattern pattern = Pattern.compile(regex);

for (String card : cards)
	//Strip all hyphens
	card = card.replaceAll("-", "");

	//Match the card
	Matcher matcher = pattern.matcher(card);


	if(matcher.matches()) {
		//If card is valid then verify which group it belong 

3. Checksum Validation with the Luhn Algorithm

There is an extra validation check that you can do on the credit card number before processing the order. The last digit in the credit card number is a checksum calculated according to the Luhn algorithm. Since this algorithm requires basic arithmetic, you cannot implement it with a regular expression.

Below is the method which you can use to run checksum validation using Luhn Algorithm. This function takes a string with the credit card number as a parameter. The card number should consist only of digits.

The actual algorithm runs on the array of digits, calculating a checksum. If the sum modulus 10 is zero, then the card number is valid. If not, the number is invalid.

I have taken the reference implementation of Luhn Algo from Google Code.

public class Luhn
	public static boolean Check(String ccNumber)
		int sum = 0;
		boolean alternate = false;
		for (int i = ccNumber.length() - 1; i >= 0; i--)
			int n = Integer.parseInt(ccNumber.substring(i, i + 1));
			if (alternate)
				n *= 2;
				if (n > 9)
					n = (n % 10) + 1;
			sum += n;
			alternate = !alternate;
		return (sum % 10 == 0);

Feel free to modify above code samples to match other validation rules in above regex, if you need it.

Happy Learning !!


Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.