ash
ash

Reputation: 23

Regex for credit card requiring same repeat symbols

I am struggling to find and come up with a regex that disallows inconsistent symbols in credit cards.

\d{4}[\s\-]*\d{4}[\s\-]*\d{4}[\s\-]*\d{4}

For example, the Regex above allows for the below to pass. The last one is problematic as it contains '-' and ' ' and ''. How do I come up with a regex that requires all the symbols ('-' or ' ' or '') to be consistently the same? i.e. only allow the first 3 but not the last statement.

1234123412341234, 1234-1234-1234-1234, 1234 1234 1234 1234, 1234-12341234 1234

Upvotes: 2

Views: 69

Answers (1)

Alex
Alex

Reputation: 632

You can use a capture group to "remember" what the separator was in the first case, and ensure that the other cases also use it.

The final regex is: \d{4}([\s\-])*\d{4}\1*\d{4}\1*\d{4}

The () around the first [\s\-] start the capture group; the \1 later on indicates to use the same value as was previously captured.

See it in action here https://regexr.com/5l74g

Edit: per the comments, a better solution might be \d{4}([\s\-]?)\d{4}\1\d{4}\1\d{4}, depending on what exactly your requirements are. This one ensures that -s and s are not mixed, and also that there is only 0 or 1 separators.

Upvotes: 2

Related Questions