27: </script>
28:</head>
29:<body>
30: <form name="testform" id="testform" method="post" action=""
31: onsubmit="return(checkipaddress(
window.document.testform.ipaddress.value));">
32: <center>
33: enter an ip address: <input type="text" name="ipaddress"
id="ipaddress" value="" /><br />
34: <input type="submit" name="submitbutton" id="submitbutton"
value="enter" />
35: </center>
36: </form>
37:</body>
38:</html>
第7行代码创建正则表达式对象。但这次表达式的类型不同。小括号()里的参数是为后面的子测试用的。"\d"表示数字匹配,"\d+"则要求至少匹配一个数字。在测试输入值匹配之后,用子测试确定每个节的数字都在0 - 255之间。子测试时用到全局对象regexp,它在调用string.match方法时自动生成。
使用vbscript要多写些代码,但也能实现同样的功能。
服务端vbscript匹配校验代码:
01:<%@ language = vbscript
02: enablesessionstate = false%>
03:<!-- test2.asp file -->
04:<%
05:dim ipaddress
06:dim reipaddresscheck
07:dim formpost
08:dim passedtest
09:dim matches
00:dim num1
11:dim num2
12:dim num3
13:dim num4
14:
15:if request.form.item("submitbutton") = "enter" then
16: formpost = true
17:else
18: formpost = false
19:end if
20:
21:if formpost then
22: ipaddress = request.form.item("ipaddress")
23: set respacecheck = new regexp
24: respacecheck.pattern = "^(\d+)\.(\d+)\.(\d+)\.(\d+)$"
25:
26: if respacecheck.test(ipaddress) then
27: set matches = respacecheck.execute(ipaddress)
28: num1 = matches.item(0).submatches.item(0)
29: num2 = matches.item(0).submatches.item(1)
30: num3 = matches.item(0).submatches.item(2)
31: num4 = matches.item(0).submatches.item(3)
32: if num1 <= 255 and num1 >= 0 _
33: and num2 <= 255 and num2 >= 0 _
34: and num3 <= 255 and num3 >= 0 _
35: and num4 <= 255 and num4 >= 0 then
36: passedtest = true
37: end if
38: end if
39:end if
40:%>
41:<html>
42:<head>
43: <title>match example</title>
44:</head>
45:<body>
46: <center>
47: <%if formpost then
48: if passedtest then%>
49: <b>you entered <%=ipaddress%> as a valid ip address.</b>
50: <%else%>
51: <b><font color="red">you must enter a valid ip address.</font></b>
52: <%end if%>
53: <br />
54: <%end if%>
55: <form name="testform" id="testform" method="post" action="test2.asp">
56: enter an ip address: <input type="text" name="ipaddress" id="ipaddress"
value="" /><br />
57: <input type="submit" name="submitbutton" id="submitbutton" value="enter" />
58: </form>
59: </center>
60:</body>
61:</html>
与javascript不同, vbscript没有match命令。所以用正则表达式的execute方法来处理匹配测试。execute返回结果中包含四个子数组,对应于每节数字的检测结果。然后检测该节数字是否在0 - 255范围内。检测无误,就得到正确的ip地址。
通过本文,希望有助于初步了解正则表达式的用法。可在微软站点下载有关脚本帮助文件。
happy programming!