如何在nodejs中将多个string与一个正则expression式匹配?

我的问题

我一直困惑的下面的代码片段。 string似乎是相同的正则expression式(唯一的区别是一个数字应该与\d匹配。实际上,第一个string匹配,而第二个string不匹配。

玩过之后,很明显顺序很重要:只匹配第一个string。

 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)); 

我的问题

我怎样才能使用相同的正则expression式来匹配多个string,而不用担心之前的匹配可能会改变匹配?

在正则expression式中使用“g”标志时,.exec()将返回一个索引到正则expression式对象的lastIndex属性中。 然后,当您尝试使用相同的正则expression式再次使用.exec()时,它将开始在lastIndex中指定的索引处进行search。

有几种方法可以解决这个问题:

 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