SBB
SBB

Reputation: 8970

Regex Giftcard number pattern

I am trying to come up with a regex for a giftcard number pattern in an application. I have this so far and it works fine:

(?:5049\d{12}|6219\d{12}) = 5049123456789012

What I need to account for though is numbers that are separated by dashed or spaces like so:

5049-1234-5678-9012

5049 1234 5678 9012

Can I chain these patterns together or do I need to make separate for each type?

Upvotes: 1

Views: 369

Answers (3)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Try this :

(?:(504|621)9(\d{12}|(\-\d{4}){3}|(\s\d{4}){3}))

https://regex101.com/r/SyjaT5/6

Upvotes: 0

Andreas
Andreas

Reputation: 159185

Use (?:5049|6219)(?:[ -]?\d{4}){3}

First, match one of the two leads. Then match 3 groups of 4 digits each, each group optionally preceded by space or dash.

See regex101 for demo, and also explains in more detail.

The above regex will also match if separators are mixed, e.g. 5049 1234-5678 9012. If you don't want that, use

(?:5049|6219)([ -]?)\d{4}(?:\1\d{4}){2}   regex101

This captures the first separator, if any, and specifies that the following 2 groups must use that same separator.

Upvotes: 2

Adriano Martins
Adriano Martins

Reputation: 1808

The easiest and most simple regex could be:

(?:(5049|6219)([ -]?\d{4}){3})

Explanation:
(5049|6219) - Will check for the '5049' or '6219' start
(x){3} - Will repeat the (x) 3 times
[ -]? - Will look for " " or "-", ? accepts it once or 0 times
\d{4} - Will look for a digit 4 times

A more detailed explanation and example can be found here: https://regex101.com/r/A46GJp/1/

Upvotes: 4

Related Questions