当前位置: 首页 > 图文教程 > 网络编程 > 正则表达式 > ASP 正则表达式常用的几种方法(execute、test、replace)

正则表达式
DreamWeaver中使用正则技术搜索
代替正则——HyperScriptExpression联合开发倡议公告
正则入门连载!(献给不及格的程序员们)
请教一个正则表达式,匹配所有Html标签外部的指定字符串
php正则表达式中的非贪婪模式匹配
js中2005-05-02怎么转换为2005/5/2?
用正则表达式格式化html标签的代码
php利用正则表达式取出图片的URL
用正则取出html页面中script段落里的内容
学习正则表达式30分钟入门教程(第二版)
只能是字母或数字或者是字母和数字的组合的正则previousSibling
[php]正则表达式的五个成功习惯
常用正则表达式语法例句
正则表达式基础教程 regular expression
php中正则表达式中的特殊符号
PHP和正则表达式教程集合之一
PHP和正则表达式教程集合之二
用正则实现提取代码内容的代码
php正则之函数 preg_replace()参数说明
关于preg_replace函数的问题讲解

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 173 ::
收藏到网摘: n/a

asp下正则表达式常用的几种方法,需要的朋友可以参考下。 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"))