首页 > 代码库 > 对正则表达式练习器的改进

对正则表达式练习器的改进


对正则表达式练习器的改进,原贴ID901680

覆盖原execIt函数
修改后的execIt函数允许对多个正则表达式进行匹配(每个正则表达式一行),并对每一个匹配成分显示出是第几个正则表达式匹配的。
这可视为语法分析的雏形,只要对匹配产生相应的动作。

function execIt(form) {
var mode
if(form.chkmode.checked) mode = "gi"
else mode = "g"
var regexpArray = form.regexp.value.split("\r\n") //获取正则表达式到数组

if(nextpoint == 0) form.reglist.value = http://www.mamicode.com/""
var key = true
if(form.scankmode.checked) key = false
else nextpoint = 0
do {
var offs = 9999999999
var pos = -1
var input = form.main.value.substr(nextpoint)
//对每个正则表达式进行匹配
for(var i=0;i<regexpArray.length;i++) {
re.compile(regexpArray[i],mode)
var matchArray = re.exec(input)
if(matchArray) {
if(offs > matchArray.index) {
offs = matchArray.index
pos = i //保存距离起始位子最近的匹配
}
}
}
if(pos>=0) {
re.compile(regexpArray[pos],mode)
var matchArray = re.exec(input)
for(var i=1;i<matchArray.length;i++)
matchArray[i] = "$"+i+":"+matchArray[i]
form.reglist.value = http://www.mamicode.com/"["+(pos+1)+"]"+(nextpoint+matchArray.index)+" => " + matchArray[0] +"/n"+form.reglist.value
form.matchlist.value = http://www.mamicode.com/"$0:"+matchArray.join("/n")
nextpoint = nextpoint + matchArray.index + matchArray[0].length
}else {
if(!key)
form.reglist.value = http://www.mamicode.com/"没有找到/n" + form.reglist.value
form.matchlist.value = http://www.mamicode.com/" "
nextpoint = 0
key = false
}
}while(key)
}