正則 對Regex練習器的改進,原貼ID901680
覆蓋原execIt函數
修改後的execIt函數允許對多個Regex進行匹配(每個Regex一行),並對每一個匹配成分顯示出是第幾個Regex匹配的。
這可視為文法分析的雛形,只要對匹配產生相應的動作。
function execIt(form) {
var mode
if(form.chkmode.checked) mode = "gi"
else mode = "g"
var regexpArray = form.regexp.value.split("\r\n") //擷取Regex到數組
if(nextpoint == 0) form.reglist.value = ""
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)
//對每個Regex進行匹配
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 = "["+(pos+1)+"]"+(nextpoint+matchArray.index)+" => " + matchArray[0] +"\n"+form.reglist.value
form.matchlist.value = "$0:"+matchArray.join("\n")
nextpoint = nextpoint + matchArray.index + matchArray[0].length
}else {
if(!key)
form.reglist.value = "沒有找到\n" + form.reglist.value
form.matchlist.value = " "
nextpoint = 0
key = false
}
}while(key)
}