正则表达式的用途很广泛,但要熟练掌握就不是一件容易的事情了。为此,我编写了这个练习器用来帮助学习。
请多指教!
*********将以下代码复制到 RegExp.htm 即可 **********
<HTML>
<HEAD>
<TITLE>正则表达式练习器</TITLE>
<meta name = 安徽 池州 统计局 徐祖宁 e-mail:czjsz@stats.gov.cn>
<script language="JavaScript">
function OnMove() {
window.status = "("+window.event.clientX+","+window.event.clientY+")" + " :: "+document.location
}
</script>
<SCRIPT LANGUAGE="JavaScript1.2">
var re = new RegExp() //建立正则表达式对象
var nextpoint = 0 //匹配时的偏移量
//设置正则表达式
function setPattern(form) {
var mode
if(form.chkmode.checked) mode = "gi" //i:不分大小写 g:全局,好象没什么作用
else mode = "g"
re.compile(form.regexp.value,mode)
nextpoint = 0
form.reglist.value = ""
}
//检查是否有匹配
function findIt(form) {
setPattern(form)
var input = form.main.value
if (input.search(re) != -1) {
form.output[0].checked = true
} else {
form.output[1].checked = true
}
}
//检查匹配位置
function locateIt(form) {
setPattern(form)
var input = form.main.value
form.offset.value = input.search(re)
}
//检查所有的匹配情况
function execIt(form) {
if(nextpoint == 0 || ! form.scankmode.checked) {
findIt(form)
form.reglist.value = ""
}
var key = true
if(form.scankmode.checked) key = false
do {
var input = form.main.value
var matchArray = re.exec(input.substr(nextpoint))
if(matchArray) {
for(var i=1;i<matchArray.length;i++)
matchArray[i] = "$"+i+":"+matchArray[i]
form.reglist.value = (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)
}
//设置当前使用的正则表达式
function setregexp(n) {
var s = document.all.regexplist.value.split("\r\n")
document.all.regexp.value = s[n*2-1] //.replace("\r","")
nextpoint = 0
}
//定义选择监视
var isNav = (navigator.appName == "Netscape")
function showSelection() {
if (isNav) {
var theText = document.getSelection()
} else {
var theText = document.selection.createRange().text
}
if(theText.length>0 && document.all.selechkmode.checked)
document.all.regexp.value = theText
}
if (isNav) {
document.captureEvents(Event.MOUSEUP)
}
doc