對正則表達式練習器的改進,原貼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 = "" 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 = "["+(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) }
|