星空网 > 软件开发 > Java

对match() 和 exec() 返回值和属性的测试

 

语法:
exec() :
RegExpObject.exec(string)

match() :
stringObject.match(string)stringObject.match(regexp)

 
知识点:
exec() 是RegExp对象的方法,而 match()  是String对象的方法。
都会返回包含第一个匹配项信息的数组;或者在没有匹配项的情况下返回null。
返回的数组虽然是Array 的实例,但包含两个额外的属性:index 和 input。其中,index 表示匹配项在字符串中的位置,而 input 表示应用正则表达式的字符串。
在数组中,第一项是与整个模式匹配的字符串,其他项是与模式中的捕获组匹配的字符串(如果模式中没有捕获组,则该数组只包含一项)。
 
测试:
对 match() 的测试代码:
var text = "mom and dad and baby";
var pattern = /(mom and )?(dad and )?baby/;
 
var matches = text.match(pattern);//pattern.exec(text);
console.log(matches.index);
console.log(matches.input);
console.log(matches[0]);
console.log(matches[1]);
console.log(matches[2]);


 

对 match() 的测试结果截图:
对match() 和 exec() 返回值和属性的测试

对 exec() 的测试代码:
var text = "mom and dad and baby";
var pattern = /(mom and )?(dad and )?baby/;
 
var matches = pattern.exec(text);//text.match(pattern);
console.log(matches.index);
console.log(matches.input);
console.log(matches[0]);
console.log(matches[1]);
console.log(matches[2]);


 

对 exec() 的测试结果截图:
对match() 和 exec() 返回值和属性的测试
其他相关方法:

RegExp 对象方法

方法描述
exec检索字符串中指定的值。返回找到的值,并确定其位置
test检索字符串中指定的值。返回 true 或 false。

 

String 对象方法


方法描述
match()找到一个或多个正则表达式的匹配。
replace()替换与正则表达式匹配的子串。
search()检索与正则表达式相匹配的值。

 
 



原标题:对match() 和 exec() 返回值和属性的测试

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

建筑建材:https://www.goluckyvip.com/tag/34628.html
剑牛科技:https://www.goluckyvip.com/tag/34629.html
Flipkart:https://www.goluckyvip.com/tag/3463.html
健达巧克力:https://www.goluckyvip.com/tag/34630.html
健康云:https://www.goluckyvip.com/tag/34631.html
江门fba头程物流:https://www.goluckyvip.com/tag/34632.html
去日本入住酒店,东西随意用却有一个特殊“要:https://www.vstour.cn/a/411241.html
中国有哪些著名的酒店品牌。:https://www.vstour.cn/a/411242.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流