exec 方法
使用正则表达式模式对字符串执行查找,并返回该查找结果的第一个值(数组),如果匹配失败,返回null。
rgExp.exec(str)
参数:
str 必选项。对其进行查找的 String 对象或字符串文字。
rgExp 必选项。为包含正则表达式模式和可用标志的正则表达式对象。
返回数组包含:
input:整个被查找的字符串的值;
index:匹配结果所在的位置(位);
lastInput:下一次匹配结果的位置;
arr:结果值,arr[0]全匹配结果,arr[1,2...]为表达式内()的子匹配,由左至右为1,2...。
例1:
<!DOCTYPE html> <html> <head> <title>ExecDemo</title> <script type="text/javascript" language="JavaScript"> function ExecDemo(){ var r, re; var s="The rain in Spain falls mainly in the plain"; //创建正则表达式模式。 g 代表全部匹配 并且不含子匹配项 re = /\w+/g; while((r = re.exec(s)) !=null){ //exec使r返回匹配的第一个,while循环一次将使re在g作用寻找下一个匹配。 document.write(r.index + "-" + r.lastIndex + ":" + r + "<br/>"); for(key in r){ document.write(key + "=>" + r[key] + "<br/>"); } document.write("<br/>"); } //测试exec的输出将包含子匹配项 re = /[\w]*(ai)n/ig; r = re.exec(s); document.write("<br/>"); document.write(r + "<br/>"); for(key in r){ document.write(key + "-" + r[key] + "<br/>"); } } </script> </head> <body onload="ExecDemo()"> </body> </html>
输出结果:
0-3:The input=>The rain in Spain falls mainly in the plain index=>0 lastIndex=>3 0=>The 4-8:rain input=>The rain in Spain falls mainly in the plain index=>4 lastIndex=>8 0=>rain 9-11:in input=>The rain in Spain falls mainly in the plain index=>9 lastIndex=>11 0=>in 12-17:Spain input=>The rain in Spain falls mainly in the plain index=>12 lastIndex=>17 0=>Spain 18-23:falls input=>The rain in Spain falls mainly in the plain index=>18 lastIndex=>23 0=>falls 24-30:mainly input=>The rain in Spain falls mainly in the plain index=>24 lastIndex=>30 0=>mainly 31-33:in input=>The rain in Spain falls mainly in the plain index=>31 lastIndex=>33 0=>in 34-37:the input=>The rain in Spain falls mainly in the plain index=>34 lastIndex=>37 0=>the 38-43:plain input=>The rain in Spain falls mainly in the plain index=>38 lastIndex=>43 0=>plain rain,ai input-The rain in Spain falls mainly in the plain index-4 lastIndex-8 0-rain 1-ai
转载于:https://blog.51cto.com/chcchb/1329921