JS正则表达式global修饰符概述
本示例深入解析JavaScript正则表达式中global(/g)修饰符的具体应用。内容旨在提供实用的参考指南,帮助开发者理解其核心机制。
/g标志表示启用全局搜索功能,即持续查找所有符合条件的子串,而不是在定位到首个匹配项后立即终止。以下通过一段典型代码进行演示:
var str = "123#abc";
var noglobal = /abc/i;//非全局匹配模式
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出ture
var re = /abc/ig;//全局匹配
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出false
console.log(re.test(str)); //输出ture
console.log(re.test(str)); //输出false
观察发现,当采用/g模式时,反复调用RegExp.test()方法所得到的布尔返回值会出现波动。相关原理阐释引用自《Javascript中正则表达式的全局匹配模式分析》一文:
若在构建正则对象时指定了“g”标识符,或将其global属性设为true,则该对象将对目标字符串执行全局匹配流程。在此模式下,可针对同一字符串进行多次匹配操作。每次匹配均依据正则对象内部lastIndex属性的当前值,确定在源字符串中的起始检索点。lastIndex初始值为0,成功匹配后,其值更新为匹配内容末尾字符后的索引位置,以此标记下一次匹配的起点。若未找到匹配项,lastIndex将被重置为0。未启用全局标志时,lastIndex恒为0,每次仅检索字符串开头的第一个匹配项。
借助下述代码片段,可以直观验证lastIndex在全局模式下的动态变化过程:
var str = "012345678901234567890123456789";
var re = /123/g;
console.log(re.lastIndex); //输出0,正则表达式刚开始创建
console.log(re.test(str)); //输出ture
console.log(re.lastIndex); //输出4
console.log(re.test(str)); //输出true
console.log(re.lastIndex); //输出14
console.log(re.test(str)); //输出ture
console.log(re.lastIndex); //输出24
console.log(re.test(str)); //输出false
console.log(re.lastIndex); //输出0,没有找到匹配项被重置
前述内容展示了/g模式如何改变RegExp.test()的行为逻辑。接下来考察其对RegExp.exec()函数的影响。exec()方法返回包含匹配信息的数组;若未命中任何匹配,则返回null。
var str = "012345678901234567890123456789";
var re = /abc/;
//exec没有找到匹配
console.log(re.exec(str));//null
console.log(re.lastIndex);//0
var str = "012345678901234567890123456789";
var re = /123/;
var resultArray = re.exec(str);
console.log(resultArray[0]);//匹配结果123
console.log(resultArray.input);//目标字符串str
console.log(resultArray.index);//匹配结果在原始字符串str中的索引
对于exec方法,若不设置g标志,无论调用多少次,始终只返回第一个匹配结果;若设置了g标志,首次调用返回第一个匹配,后续调用依次返回第二个、第三个等,依此类推。
var str = "012345678901234567890123456789";
var re = /123/;
var globalre = /123/g;
//非全局匹配
var resultArray = re.exec(str);
console.log(resultArray[0]);//输出123
console.log(resultArray.index);//输出1
console.log(globalre.lastIndex);//输出0
var resultArray = re.exec(str);
console.log(resultArray[0]);//输出123
console.log(resultArray.index);//输出1
console.log(globalre.lastIndex);//输出0
//全局匹配
var resultArray = globalre.exec(str);
console.log(resultArray[0]);//输出123
console.log(resultArray.index);//输出1
console.log(globalre.lastIndex);//输出4
var resultArray = globalre.exec(str);
console.log(resultArray[0]);//输出123
console.log(resultArray.index);//输出11
console.log(globalre.lastIndex);//输出14
在使用/g匹配模式时,开发人员可以利用循环结构遍历并提取所有的匹配项。
var str = "012345678901234567890123456789";
var globalre = /123/g;
//循环遍历,获取所有匹配
var result = null;
while ((result = globalre.exec(str)) != null)
{
console.log(result[0]);
console.log(globalre.lastIndex);
}
补充推荐两款实用的正则表达式辅助工具供读者使用:
JavaScript正则表达式在线测试平台: 点击使用
期望上述关于JavaScript编程技巧的分享能为大家的实际开发工作带来助益。