ncaught TypeError: Cannot read properties of null (reading '0')

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图

let str2 = 'mom and dad and baby';
let rex3 = /mom( and dad (and baby)?)?/g;
console.log(rex3.exec(str2));
console.log(rex3.exec(str2)[0])
console.log(rex3.exec(str2)[1]);
console.log(rex3.exec(str2)[2]);
运行结果及报错内容 Uncaught TypeError: Cannot read properties of null (reading '0')
我的解答思路和尝试过的方法 为什么报错呢
我想要达到的结果

把正则g选项去掉,增加g选项后,会从上一次匹配的位置开始查找,所以第一句console.log打印是正常的

第二次rex3.exec(str2),会从上一次的结尾位置继续往后找,由于没有内容exec无法匹配返回null,再通过下标获取null的值就报错了

img


    let str2 = 'mom and dad and baby';
    let rex3 = /mom( and dad (and baby)?)?///g;//去掉全局匹配,要么会从上一的匹配位置继续往后查找
    console.log(rex3.exec(str2));
    console.log(rex3.exec(str2)[0])
    console.log(rex3.exec(str2)[1]);
    console.log(rex3.exec(str2)[2]);

img

返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。
你第一个打印是否匹配上了?未匹配的话是无法获取下标为0的数组