首页 > 解决方案 > 正则表达式(Javascript)允许忽略逗号

问题描述

const value = 'I am a student. My age is 5';
const regex = new RegExp('\\b' + value, 'i'); //what to add here?

console.log(regex.test('I am a student, my age is 5')); //true
console.log(regex.test('I am a student my age is 5')); //false

我想忽略,使我的第二个字符串为真。

标签: javascriptregex

解决方案


你可能想要一个更通用的正则表达式,像这样:

const regex =  /^I am a \w+[.,]? My age is \d+$/i

console.log(regex.test('I am a student, my age is 5')); //should be true
console.log(regex.test('I am a student my age is 5')); //should be true
console.log(regex.test('I am a INSERTWORD my age is 5')); //should be true
console.log(regex.test('I am a student my age is 230')); //should be true

一个不太通用的正则表达式可能如下所示:

const regex =  /^I am a student[.,]? My age is 5$/i

console.log(regex.test('I am a student, my age is 5')); //should be true
console.log(regex.test('I am a student my age is 5')); //should be true
console.log(regex.test('I am a INSERTWORD my age is 5')); //should be false
console.log(regex.test('I am a student my age is 230')); //should be false

如果您想了解有关正则表达式的更多信息,请访问以下之一:

https://regex101.com/ regex 101 是我要去的正则表达式测试网站。

https://www.regextester.com/

https://regexr.com/


推荐阅读