正規表現を利用するプログラムを作る時は、正規表現の部分だけで意図した通りの動作をするか確認してからプログラムを作ると作業がスムーズに進みます。
正規表現だけで動作確認するためのプログラムを作成しました。
実行画面

最上段のテキストエリアが「textarea」です。
「res = textarea.match(RE)」ボタンを押すと上図のようにmatchの結果が表示されます。
以下ソース
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<title>RegExp</title> | |
<style> | |
.max{width:100%;height:100%} | |
.w-max{width:100%} | |
.nowrap{white-space:nowrap} | |
.ta-c{text-align:center} | |
.bc{border-collapse:collapse} | |
</style> | |
<body style="overflow:hidden"> | |
<table class="max bc"> | |
<tr><td><textarea id=ta0 wrap=off class=max></textarea></td></tr> | |
<tr height=1> | |
<td> | |
<table class="w-max bc"> | |
<td width=1><span class=nowrap>RE = new RegExp(</span></td> | |
<td><input class=w-max id=inpRE></td> | |
<td width=1>,</td> | |
<td width=1> | |
<label><input type=checkbox id=chkG>g</label> | |
<label><input type=checkbox id=chkI>i</label> | |
</td> | |
<td width=1><span class=nowrap>);</span></td> | |
</table> | |
</td> | |
</tr> | |
<tr height=1><td class=ta-c><button id=btnM>res = textarea.match(RE)</button></td></tr> | |
<tr id=tr0><td class=ta-c>match箇所無し</td></tr> | |
<tr id=tr1 height=1> | |
<td> | |
<table class="w-max bc" border=1> | |
<tr> | |
<td>res</td> | |
<td><textarea id=taRes class=w-max wrap=off style="height:100px"></textarea></td> | |
</tr> | |
<tr> | |
<td>res[n]</td> | |
<td><div id=divResN style="height:100px;overflow:auto"></div></td> | |
</tr> | |
<tr><td>lastMatch</td><td id=tdLM></td></tr> | |
<tr><td>lastParen</td><td id=tdLP></td></tr> | |
<tr> | |
<td width=1><span class=nowrap>rightContext</span></td> | |
<td><textarea id=taRC class=w-max style="height:100px" wrap=off></textarea></td> | |
</tr> | |
</table> | |
</td> | |
</tr> | |
</table> | |
</body> | |
<script> | |
resizeTo(400,600) | |
iT='innerText', iH='innerHTML', FI='firstChild', CN='childNodes' | |
tr0.style.display = tr1.style.display = 'none' | |
btnM.onclick=function(){ | |
var RE=new RegExp(inpRE.value, (chkG.checked ? 'g' : '') + (chkI.checked ? 'i' : '')), str=ta0.value, res=str.match(RE) | |
if(!res){ | |
tr0.style.display = 'block' | |
tr1.style.display = 'none' | |
return | |
} | |
tr0.style.display = 'none' | |
tr1.style.display = 'block' | |
divResN[iH] = '<table class="max bc" border=1><td width=1></td><td></td></table>' | |
var tbo=divResN[FI][FI], tr=tbo[FI].removeNode(true), i=0, L=res.length, newTR | |
for(;i<L;i++){ | |
tbo.insertBefore(newTR=tr.cloneNode(true)) | |
newTR[CN][0][iT] = i | |
newTR[CN][1][iT] = res[i] | |
} | |
setTimeout(function(){ | |
with(RegExp){ | |
taRes.value = res | |
tdLM[iT] = lastMatch | |
tdLP[iT] = lastParen | |
taRC.value = rightContext | |
} | |
},1) | |
} | |
</script> | |
</html> |
0 件のコメント:
コメントを投稿