RegEx to find credit card numbers with embedded spaces

喜欢而已 提交于 2021-02-20 00:43:46

问题


We currently have a content compliance in place where by we monitor anything that contains a credit card number with no spaces (e.g 5100080000000000)

What we need is for a reg ex to pick up credit card numbers that are entered with spaces every 4 digits (eg: 5100 0800 0000 0000)

We've been looking at alternate reg exs but have not yet found one that works for both scenarios mentioned above.

The current reg ex we use is below

^((4\d{3})|(5[1-5]\d{2})|(6011)|(34\d{1})|(37\d{1}))-?\d{4}-?\d{4}-?\d{4}|3[4,7][\d\s-]{15}$


回答1:


Just add optional /s? in where you already have the optional -?

So your regex becomes

^((4\d{3})|(5[1-5]\d{2})|(6011)|(34\d{1})|(37\d{1}))-?\s?\d{4}-?\s?\d{4}-?\s?\d{4}|3[4,7][\d\s-]{15}$



回答2:


It seems that you already accept a dash every four characters. Thus you can simply replace -? with [- ]? everywhere.

If you require the dashes or spaces to be consistent - that is, allow no grouping at all, or a dash every four characters, or a space every four characters, you can use a back reference to force the repetitions to be identical to the first match:

^(?:4\d{3}|5[1-5]\d{2}|6011|3[47]\d{2})([- ]?)\d{4}\1\d{4}\1\d{4}$

You will notice I removed the final 3[4,7]... which looked like an erroneous addition, apparently made when attempting to solve this problem partially. Also I changed the parentheses to non-grouping ones (?:...) or simply removed them where no grouping seemed necessary or useful, mainly because this makes it easier to see what the backreference \1 refers to. Finally, the 34.. and 37.. patterns had \d{1} where apparently \d{2} was intended (or if those particular series are only three digits before the first dash, the repetition {1} was just superfluous, but then the 3[4,7]... part would have been even more wrong!)




回答3:


Won't all these ideas blow up on you as soon as someone uses and AMEX card and enters 3 or 5 numbers instead of 4 in any one 'block'




回答4:


((\d+) *(\d+) *(\d+) *(\d+))

That would be the general idea (and it even works!), you can polish it if you want. There is a great page to test your regexp live - http://rubular.com/




回答5:


Try this:

(\d{4} *\d{4} *\d{4} *\d{4})


来源:https://stackoverflow.com/questions/16569397/regex-to-find-credit-card-numbers-with-embedded-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!