Javascript的正则表达式是有状态的!
var res, text = "name leo1 leo2 leo3", regexp = /leo(\d)/g; console.log("regexp.lastIndex:", regexp.lastIndex); while (res = regexp.exec(text)) { console.log("regexp.lastIndex:", regexp.lastIndex, "index:", res.index, "res[0]:", res[0], "res[1]:", res[1]); } console.log("regexp.lastIndex:", regexp.lastIndex); 结果: regexp.lastIndex: 0 regexp.lastIndex: 9 index: 5 res[0]: leo1 res[1]: 1 regexp.lastIndex: 14 index: 10 res[0]: leo2 res[1]: 2 regexp.lastIndex: 19 index: 15 res[0]: leo3 res[1]: 3 regexp.lastIndex: 0
test 要比 exec 快,所以代码修改如下:
var res, text = "name leo1 leo2 leo3", regexp = /leo(\d)/g,lastIndex = regexp.lastIndex; console.log("regexp.lastIndex:", regexp.lastIndex); while (regexp.test(text)) { regexp.lastIndex = lastIndex; res = regexp.exec(text) console.log("regexp.lastIndex:", regexp.lastIndex, "index:", res.index, "res[0]:", res[0], "res[1]:", res[1]); lastIndex = regexp.lastIndex; } console.log("regexp.lastIndex:", regexp.lastIndex);
var text = "jsera net jsera net jsera net", greedyRegexp = /jsera.*net/g, nonGreedyRegexp = /jsera.*?net/g; console.log(text.match(greedyRegexp)); console.log(text.match(nonGreedyRegexp)); 结果 [ 'jsera net jsera net jsera net' ] [ 'jsera net', 'jsera net', 'jsera net' ]