Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65932474/regex-for-credit-card-requiring-same-repeat-symbols

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}1d{4}1d{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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...