本文实例讲述了javascript字符串循环匹配的方法。分享给大家供大家参考。具体如下:
采用exec和string.match方法,对于exec必须开启全局匹配g标识才能获取所有匹配
// 需要提取这种数据 2012-12-17 11:02 , 12:25 , 13:22 , 15:06 , 15:12 , 19:22 , 23:47 var rawdata = '日期签到签退时间
' + '2012-12-03 10:16 , 13:22 , 20:05
' + '2012-12-04 11:16 , 14:22 , 21:05
';// 方法一var regexp = /(\d{4}-\d{2}-\d{2})(.*?)/g;// 加上g标识才会全局匹配,否则只匹配一个var matchedarray = regexp.exec(rawdata);while(matchedarray != null) { console.dir(matchedarray); matchedarray = regexp.exec(rawdata);}// 方法二var regexp = /(\d{4}-\d{2}-\d{2})(.*?)/g;// 加上g标识才会全局匹配var matchedarray = rawdata.match(regexp);console.dir(matchedarray);// 方法三var regexp = /(\d{4}-\d{2}-\d{2})(.*?)/;// 不加g标识var matchedarray = rawdata.match(regexp);console.dir(matchedarray);console.log(matchedarray.index);while(matchedarray != null) { rawdata = rawdata.substr(matchedarray.index + matchedarray[0].length); matchedarray = rawdata.match(regexp);}console.dir(matchedarray);
希望本文所述对大家的javascript程序设计有所帮助。
