javascript - 正则表达式(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
我想忽略,
使我的第二个字符串为真。
解决方案
你可能想要一个更通用的正则表达式,像这样:
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 是我要去的正则表达式测试网站。
推荐阅读
- scala - 如何使 sbt 输出详细日志信息
- python - GUROBI - 如何与 50 个效率最低的提供商一起运行优化
- firebase - 在 Firebase 数据库中导入多个 JSON 文件
- laravel - 推荐两个模型的雄辩关系
- android - 从android studio的内部存储器中自动读取文件?
- php - 无法接受下拉列表中的值
- mp3 - 如何使用lame.h中的preset_mode?
- r - 递归特征消除 - 线性模型 - R
- react-native - 调用 pop 以路由 NavigatorIOS 中不存在的路由以响应本机
- sql - Sqlcmd:错误:Microsoft ODBC Driver 11 for SQL Server:用户“sa”登录失败