eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

In this article, we’ll learn how to identify a credit card type from a credit card number using regex.

Then, we’ll learn about the Luhn algorithm and how we can use this to check whether a credit card number is valid.

2. What Do the Leading Digits of a Card Number Tell Us?

The Primary Account Number (PAN) is another name for a credit card number.

The PAN is typically 16 digits long, although the number of digits can vary depending on the card issuer.

Currently, the Issuer Identification Number (IIN) is the first six digits of a PAN. It’s made up of one leading digit, followed by five digits.

It’s important to emphasize that this is the current situation because it’s likely to change in the future. Work began as early as 2015 to increase the IIN to the first eight digits.

Let’s see how we can determine the type of credit card just by looking at the IIN.

2.1. What Does the Leading Digit Tell Us?

The Major Industry Identifier is the first digit of a card number.

As the name suggests, we can look at the first digit of the card number to determine the industry to which the card belongs:

  • 1, 2 – Airlines (among others)
  • 3 – Travel and Entertainment
  • 4, 5 – Banking
  • 6 – Retail and Banking
  • 7 – Fuel Industry
  • 8 – Healthcare and Telecommunications
  • 9 – National Authorities
  • 0 – Other, Reserved for the future

Now, let’s take a look at how we’d identify the card issuer using the IIN.

2.2. How Do We Determine the Card Type From the IIN?

Since 1989, there has been an international standard defining how PANs should be allocated. The official register of IINs is not publicly available.

Fortunately, the majority of leading card issuers have widely known IIN ranges, so we can use regex to match the IIN to a card issuer.

Before we look at the regex, let’s remember that the list of IIN ranges is constantly changing.

If we’re writing an application to do this, we’ll need to consider how we plan to keep it up-to-date.

Alternatively, we could choose to import one of several available open source libraries, which contain more card types and are more thoroughly tested than we are likely to be able to manage ourselves. For example, using the Stripe API would mean card processing is managed for us.

2.3. Identifying the Card Issuer by Using Regex

Let’s try and identify a Visa card.

Visa card numbers start with a 4, so a simple regex to identify a Visa card would be ^4[0-9]{0,}$.

Note that in our example, we’ve not checked the length of the number. So far, we’ve assumed that the card number is valid, so the length is not something we’re validating here.

A similar pattern can be applied to identify other card issuers. For example, American Express cards begin with a 34 or a 37, so we can detect them using ^3[47][0-9]{0,}$.

Some card issuers have wider IIN ranges.

We find that Mastercard’s cards typically start with 51-55, however, within the last decade, they’ve introduced cards within the BIN range 222100-272099.

This gives us a regex of ^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$.

We can use a similar pattern to identify cards from any card issuer whose range of IINs is known.

3. What Do the Middle Digits of a Card Number Tell Us?

The full PAN consists of 3 parts: the Issue Identification Number (IIN), an Individual Account Identification Number, and a checksum digit.

Between the IIN and the final digit, we have the Individual Account Identification Number.

The issuer defines what these middle digits mean, so they’ll have different meanings across different issuers.

They indicate information like the type of account linked to the card number.

4. What Does the Final Digit of a Card Number Tell Us?

The checksum digit is the final digit of a card number.

Helpfully, the checksum digit allows us to use the Luhn algorithm to quickly identify an invalid card number.

Hans Peter Luhn developed the Luhn algorithm in the late 1950s.

It’s used to generate every modern credit card number that we use today, ensuring that every card number shares a particular property.

The Luhn algorithm uses every digit in a card number, meaning we can use it to easily determine when a given card number is invalid – even if just a single digit was entered incorrectly.

Doing this means we can limit the number of unnecessary card processing functions. This is particularly important if we are charged per transaction we request!

Let’s see how we can use the Luhn algorithm in a Java application.

4.1. How Can We Use the Luhn Algorithm to Validate a Card Number?

Let’s run through the steps involved in using the Luhn algorithm to validate a given card number.

We’ll need to take the full credit card number, including the IIN.

Starting from the rightmost digit, we’ll add all the digits together, performing a special step for every second digit.

As we’re starting from the right, we’ll need to cycle backward through the card number, identifying every second digit:

for (int i = cardNumber.length() - 1; i >= 0; i--) {
    int digit = Integer.parseInt(cardNumber.substring(i, i + 1));

    if ((cardNumber.length() - i) % 2 == 0) {
        digit = doubleAndSumDigits(digit);
    }

    sum += digit;
}

For every second digit, we must double it, and then sum the remaining digits.

Let’s see how this works for a short example of 4 digits (instead of the usual 16 digits) – let’s check whether the number 8642 would be a valid card number.

Starting with the rightmost digit, we’re going to double every second digit:

  • So for 2 (the first digit from the right), there is no change.
  • Next, we double the second digit, 4, to get 8.
  • After that, the third digit, 6, for which there is no change.
  • Lastly, we double the fourth digit, 8, to get 16.

If doubling the digit results in a two-digit number, then we need to do an extra step to get back down to a single digit – we’re going to add those digits together to produce a single-digit number, so for 16, this would be 1+6=7.

This step is the same as subtracting 9, so we can implement it in the code as:

private static int doubleAndSumDigits(int digit) {
    int ret = digit * 2;

    if (ret > 9) {
        ret -= 9;
    }

    return ret;
}

Finally, to complete our example, let’s add each number together: 2 + 8 + 6 + 7 = 23.

If the result of the Luhn algorithm is divisible by 10, then the card number is possibly valid.

We’ll return this as the result of our check:

return sum % 10 == 0;

In our case, 23 is not divisible by 10, so 8642 is not a valid card number.

In our example, the final digit, 2, would be the checksum digit.

For real card numbers, the checksum digit is calculated using the Luhn algorithm.

For example, if we change the checksum digit to a 9 to give 8649, then the result of the Luhn algorithm is 30, which is divisible by 10, so 8649 would pass our Luhn check above.

4.2. Are There Any Limitations of the Luhn Algorithm?

Of course, our check does not imply that 8649 is definitely a valid card number. Although it passes our check, it may not have been issued as an actual card by the relevant card issuer.

The only way we can definitively confirm a card number is real is by asking the card issuer.

The Luhn algorithm still provides us with a useful way to confirm when a given card number is definitely not valid.

However, there are a few edge cases where our Luhn check would fail to detect a typo in a card number.

Fortunately, these edge cases are rare enough that we’re unlikely to ever come across one in real life.

Finally, the Luhn algorithm does not consider the length of the card number.

In reality, we know that even though 8649 passes our Luhn check, it is too short to be a real credit card number.

We can implement an extra check on the length of the card number but must remember that each card issuer’s numbers can vary in length.

5. Conclusion

In this article, we looked at what each part of the card number can tell us about a credit card account.

Firstly, we learned how to identify card issuers by matching regex patterns on the leading digits. Next, we saw that we would need issuer-specific information to understand what the middle of a card number tells us about the account. Finally, we looked at how the Luhn algorithm works and implemented some code to validate a given card number.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments