Javascript REGEX在字符串和掩码中查找信用卡号

时间:2018-02-02 16:17:02

标签: javascript regex

我想搜索字符串并屏蔽信用卡以确保安全。

"Hi here is my card number its visa 4242 4242 4242 4242"
"Hi here is my card number its visa 4242424242424242"
"Hi here is my card number its visa 4242-4242-4242-4242"

应转换为:

"Hi here is my card number its visa **** **** **** 4242"

我需要在Javascript中在客户端上执行此操作。我知道网上有很多资源和问题,所以。

我找到了两个正则表达式,但两个抛出错误:"未捕获的SyntaxError:无效或意外的令牌"

"Hi here is my card number its visa 4242 4242 4242 4242".match("(\d{4}-?){4}")

"Hi here is my card number its visa 4242 4242 4242 4242".match(\b4\d{3}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}[ -]\b)

我认为表达式与JS不兼容?

我也理解他们会返回字符串,然后我会转换字符串(掩盖它),然后在原始字符串上使用简单的替换。

有人可以帮我解决这个问题的正则表达式部分吗?

2 个答案:

答案 0 :(得分:3)

See regex in use here

\b(?:\d{4}[ -]?){3}(?=\d{4}\b)
  • \b断言位置为单词边界。如果要捕获My visa is1234567812345678
  • 等案例,可以删除此项
  • (?:\d{4}[ -]?){3}完全匹配以下3次
    • \d{4}匹配任意数字4次
    • [ -]?可选择匹配空格或连字符
  • (?=\d{4}\b)确定后面是4位数的正向前瞻(并确保其后面的内容不是单词字符)。与我的第一点类似,抓住卡片后跟My visa is 1234567812345678please use it carefully等字样,然后使用(?=\d{4}(?!\d))

const r = /\b(?:\d{4}[ -]?){3}(?=\d{4}\b)/gm
const a = [
  "Hi here is my card number its visa 4242 4242 4242 4242",
  "Hi here is my card number its visa 4242424242424242",
  "Hi here is my card number its visa 4242-4242-4242-4242"
]
const subst = `**** **** **** `

a.forEach(function(s) {
  console.log(s.replace(r, subst))
})

答案 1 :(得分:0)

正则表达式可以作为字符串".."或regexp对象/../传递。 (当作为字符串传递时,它会像new RegExp("..")一样转换为RegExp对象。)

在第一种情况下,反斜杠必须加倍,因为它们在双引号之间具有特殊含义。

 "Hi here is my card number its visa 4242 4242 4242 4242".match("\\b(\\d{4}[- ]?){4}")

 "Hi here is my card number its visa 4242 4242 4242 4242".match(/\b(\d{4}[- ]?){4}/)