简体   繁体   English

检查字符串是否包含与正则表达式匹配的子字符串

[英]Check if string contains substring matching regex

I'm writing a script to check if there's occurence of amex credit card number inside a string. 我正在编写脚本来检查字符串中是否存在美国运通信用卡号码。

My code looks like this: 我的代码如下所示:

let amexRegex= /^3[47][0-9]{13}$/;

if(text.search(amexRegex) != -1){
    console.log('Found!');
} else {
    console.log('Not found!');
}

When I set text to '378734493671000' (a valid amex credit card number), script prints out Found! 当我将text设置为'378734493671000' (有效的美国运通信用卡号)时,脚本将打印出“ Found! , but if I keep that same text and add some text arround it, like this: '378734493671000 ABCDEFG' , it prints out Not found! ,但如果我保留相同的文本并在文本'378734493671000 ABCDEFG'添加一些文本,例如: '378734493671000 ABCDEFG' ,则会打印出Not found! .

What should I change in order to find occurence of substring matching the regex? 为了找到匹配正则表达式的子字符串,我应该改变什么? I don't need a index of substring matching the regex, just true\\false. 我不需要匹配正则表达式的子字符串索引,只需true \\ false。

The ^ and $ restrict matching to beginning and end of string, respectively. ^$限制匹配到字符串的开头和结尾。 It's probably enough to remove those. 删除这些可能就足够了。

您只需要删除分别匹配stat和行尾的^$

let amexRegex= /3[47][0-9]{13}/;
let amexRegex = /3[47][0-9]{13}/

if(amenxRegex.test(text) {
  console.log('Found!')
} else {
  console.log('Not found!')
}

Pay attention that only removing ^ and $ can lead to incorrect matches, such as longer numeric strings. 请注意,仅删除^$会导致不正确的匹配,例如更长的数字字符串。 You better replace them by word boundaries: 您最好用单词边界代替它们:

\b3[47][0-9]{13}\b

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM