var con= “mom and dad and baby”;
var regP= /mom (and dad (and baby)?)?/ig;
var matches = regP.exec(con);
// 问题 console.log(matches[2]);输出什么?
console.log(matches[2]);
执行结果:

console.log(matches[2]);//and baby
matches
(3) [“mom and dad and baby”, “and dad and baby”, “and baby”, index: 0, input: “mom and dad and baby”, groups: undefined]0: "mom and dad and baby"1: "and dad and baby"2: "and baby"groups: undefinedindex: 0input: "mom and dad and baby"length: 3__proto__: Array(0)
菜鸟上类似的例子:https://www.runoob.com/regexp/regexp-syntax.html

本文解析了JavaScript中的正则表达式varregP=/mom(anddad(andbaby)?)?/ig,重点讲解了如何通过matches数组获取'mom'后面跟随'anddad'和'andbaby'的可选部分。console.log(matches[2])将输出'andbaby'。

被折叠的 条评论
为什么被折叠?



