我对下面的代码段感到困惑。字符串似乎是相同的正则表达式(唯一的区别是应该与\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));
如何使用相同的正则表达式来匹配多个字符串,而不必担心之前的匹配可能会改变匹配?
答案 0 :(得分:1)
当你在正则表达式中使用'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;
请参阅此处的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec