Javascript 如何在nodejs中用单个正则表达式匹配多个字符串? 我的问题
我被下面的代码片段弄糊涂了。字符串在正则表达式方面似乎是相同的(唯一的区别是一个应该与Javascript 如何在nodejs中用单个正则表达式匹配多个字符串? 我的问题,javascript,node.js,regex,Javascript,Node.js,Regex,我被下面的代码片段弄糊涂了。字符串在正则表达式方面似乎是相同的(唯一的区别是一个应该与\d匹配的数字)。本质上,第一个字符串匹配,而第二个字符串不匹配 在使用它之后,很明显顺序很重要:只有第一个字符串是匹配的 const regex = /departure\stime\s+([\d:]+)[\s\S]*arrival\stime\s+([\d:]+)[\s\S]*Platform\s+(\S+)[\s\S]*Duration\s([\d:]+)/gm; const s1 = '\n
\d
匹配的数字)。本质上,第一个字符串匹配,而第二个字符串不匹配
在使用它之后,很明显顺序很重要:只有第一个字符串是匹配的
const regex = /departure\stime\s+([\d:]+)[\s\S]*arrival\stime\s+([\d:]+)[\s\S]*Platform\s+(\S+)[\s\S]*Duration\s([\d:]+)/gm;
const s1 = '\n departure time 05:42\n \n arrival time 06:39\n Boarding the train from Platform 3\n \n Switch train in \n No changing\n \n Change\n \n \n \n \n Access for handicapped.\n reserved seats\n \n \n Duration 00:57\n \n ';
const s2 = '\n departure time 05:12\n \n arrival time 06:09\n Boarding the train from Platform 3\n \n Switch train in \n No changing\n \n Change\n \n \n \n \n Access for handicapped.\n reserved seats\n \n \n Duration 00:57\n \n ';
console.log('Match: ', regex.exec(s1));
console.log('No Match:', regex.exec(s2));
我的问题
如何使用同一个正则表达式匹配多个字符串,而不用担心上一个匹配可能会改变匹配?当您在正则表达式中使用“g”标志时,.exec()将返回一个索引到正则表达式对象的lastIndex属性中。然后,当您尝试使用.exec()时同样,对于相同的正则表达式,它将在lastIndex中指定的索引处开始搜索 有几种方法可以克服这一问题:
1) Remove the 'g' flag. lastIndex will stay set at 0
2) Use .match(), .test(), or .search()
3) Manually reset the lastIndext after each call to .exec()
// for example:
let results = regex.exec(s1);
regex.lastIndex = 0;
请参阅此处的文档:请注意,
String.prototype.match()
和RegExp.prototype.exec()
的行为与g
标志的作用大不相同。为什么要使用“g”标志?您尝试过不使用“g”吗?您需要手动重置lastIndex,或者应该使用match。您需要使量词变懒:使用String.prototype.match
而不是RegExp.prototype.exec
。可能重复