JavaScript中String.match()与RegExp.exec()的区别详解

作者:半夏时间:2026-10-26 23:11:18浏览:137

本文详细解析JavaScript中String.match()与RegExp.exec()方法的异同。重点阐述在RegExp的global属性为false或true时,两者的返回数组结构、index/input属性以及lastIndex行为的具体差异,并通过代码示例说明如何正确使用exec进行全局匹配循环。

match与exec的基础返回机制

当匹配成功时,这两个方法均返回一个数组;若匹配失败,则返回null。


如果RegExp对象的global属性设置为false,String.match()与RegExp.exec()返回的数组内容完全一致。



该数组的第0个元素包含正则表达式模式匹配到的第一个完整字符串,后续元素则包含该匹配结果中的子匹配字符串。


此外,返回的数组还包含index和input两个额外属性:index表示匹配字符串在原字符串中的起始位置,input表示被搜索的整个原始输入字符串。


在此情况下(global为false),RegExp对象的lastIndex属性始终保持为0。


以下是global属性为false时的示例代码。


代码如下:

 
var s = 'this is a string';
var p = /\b\w*(i)s\b/;
var rm = s.match(p);
var re = p.exec(s);
console.log('match_array: ' + JSON.stringify(rm));
console.log('match_array_index: ' + rm.index);
console.log('match_array_input: ' + rm.input);
console.log('----------------------------');
console.log('exec_array: ' + JSON.stringify(re));
console.log('exec_array_index: ' + re.index);
console.log('exec_array_input: ' + re.input);

在Firefox控制台中的显示结果如下:


代码如下:

 
match_array: ["this","i"]
match_array_index: 0
match_array_input: this is a string
---------------------------- 
exec_array: ["this","i"]
exec_array_index: 0
exec_array_input: this is a string

Global标志对返回值的影响

当RegExp的global属性设置为true时,两者的返回数组结构出现显著差异。


String.match()方法返回的数组仅包含所有匹配成功的字符串,不包含子匹配字符串,也没有index和input属性。此时,RegExp对象的lastIndex属性对该方法无效。


RegExp.exec()方法返回的数组格式与global为false时相同,但此时lastIndex属性生效。匹配操作从lastIndex指定的字符位置开始,执行后会将lastIndex更新为本次匹配字符串结束后的下一个字符位置。因此,通过循环调用exec方法可以依次匹配整个字符串,直到最后返回null并将lastIndex重置为0。


以下是global属性为true时的示例代码。


代码如下:

 
var s = 'this is a string';
var p = /\b\w*(i)s\b/g;
var rm = s.match(p);
var re;
console.log('match_array: ' + JSON.stringify(rm));
console.log('match_array_index: ' + rm.index);
console.log('match_array_input: ' + rm.input);
while(re = p.exec(s)){
console.log('----------------------------');
console.log('exec_array: ' + JSON.stringify(re));
console.log('exec_array_index: ' + re.index);
console.log('exec_array_input: ' + re.input);
console.log('regexp_lastIndex: ' + p.lastIndex);
} 
console.log('----------------------------');
console.log('exec_array: ' + re);
console.log('regexp_lastIndex: ' + p.lastIndex);

运行结果如下:


代码如下:

 
match_array: ["this","is"]
match_array_index: undefined
match_array_input: undefined
---------------------------- 
exec_array: ["this","i"]
exec_array_index: 0
exec_array_input: this is a string
regexp_lastIndex: 4
---------------------------- 
exec_array: ["is","i"]
exec_array_index: 5
exec_array_input: this is a string
regexp_lastIndex: 7
---------------------------- 
exec_array: null
regexp_lastIndex: 0

综上所述:



1. 当正则表达式没有g标识符时,match和exec方法的效果基本一致;当存在g标识符时,exec方法能提供更完整的匹配结果及状态信息。


2. 顺便提及RegExp.test()方法,它是exec方法的简化版。若有匹配结果返回true,无匹配结果返回false,其执行过程与exec相同,逻辑上相当于(p.exec(s) != null)。


3. RegExp的lastIndex属性仅在带有g标识符,且在exec和test方法中有效,在其他情况下无效。

作者最新文章