当前位置: 移动技术网 > IT编程>开发语言>正则 > ASP 正则表达式常用的几种方法(execute、test、replace)

ASP 正则表达式常用的几种方法(execute、test、replace)

2017年12月12日  | 移动技术网IT编程  | 我要评论
regexp就是建立正则的对像。
如:
set regex = new regexp

regex.pattern 就是来设置正则的模式的,
如:
regex.pattern ="/d+"

regex.ignorecase = true ' 设置是否区分大小写
regex.global = true ' 设置全程可用性。


regexp对像有3种方法,分别是execute、test、replace。

test方法是对指定的字符串执行一个正则表达式搜索,并返回一个 boolean 值指示是否找到匹配的模式。regexp.global属性对test方法没有影响。如果找到了匹配的模式,test方法返回true;否则返回false。
例子:

测试的时候,msgbox是vbs的用法,如果是asp文件,需要将msgbox替换为response.write
复制代码 代码如下:

function regexptest(patrn, strng)
dim regex, retval ' 建立变量。
set regex = new regexp ' 建立正则表达式。
regex.pattern = patrn ' 设置模式。
regex.ignorecase = false ' 设置是否区分大小写。
retval = regex.test(strng) ' 执行搜索测试。
if retval then
regexptest = "找到一个或多个匹配。"
else
regexptest = "未找到匹配。"
end if
end function

msgbox(regexptest("\d+", "abcd1234"))
msgbox(regexptest("\d+", "abcd"))


replace 方法替换在正则表达式查找中找到的文本
例子:
vbs代码
复制代码 代码如下:

function replacetest(str,patrn, replstr)
dim regex, str1 ' 建立变量。
'str1 = "dog 123."
set regex = new regexp ' 建立正则表达式。
regex.pattern = patrn ' 设置模式。
regex.ignorecase = true ' 设置是否区分大小写。
replacetest = regex.replace(str, replstr) ' 作替换。
end function

msgbox(replacetest("dog 123","\d+", "cat")) '将字符串中的123替换为cat


execute 方法,则是对指定的字符串执行正则表达式搜索。这里又涉及到match对像和matches 集合。matches 集合就是match的对像集合。matches 集合中包含若干独立的 match 对象,只能使用 regexp 对象的 execute 方法来创建之。例子:
vbs测试代码
复制代码 代码如下:

function regexptest(patrn, strng)
dim regex, match, matches ' 建立变量。
set regex = new regexp ' 建立正则表达式。
regex.pattern = patrn ' 设置模式。
regex.ignorecase = true ' 设置是否区分大小写。
regex.global = true ' 设置全程可用性。
set matches = regex.execute(strng) ' 执行搜索。
for each match in matches ' 遍历 matches 集合。
retstr = retstr & match.firstindex & "。匹配的长度为"&" "
retstr = retstr & match.length &" "
retstr = retstr & matches(0) &" " '值为123
retstr = retstr & matches(1)&" " '值为44
retstr = retstr & match.value&" " '值为123和44的数组
retstr = retstr & vbcrlf
next
regexptest = retstr
end function
msgbox(regexptest("\d+", "123a44"))

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网