正则表达式的使用 ASP

复制代码 代码如下:

  <%

  ' --------------------------------------------------------------

  ' Match 对象

  ' 匹配搜索的结果是存放在 Match 对象中,提供了对正则表达式匹配的只读属性的访问。

  ' Match 对象只能通过 RegExp 对象的 Execute 方法来创建,该方法实际上返回了 Match 对象的集合。

  ' 所有的 Match 对象属性都是只读的。在执行正则表达式时,可能产生零个或多个 Match 对象。

  ' 每个 Match 对象提供了被正则表达式搜索找到的字符串的访问、字符串的长度,以及找到匹配的索引位置等。

  ' ○    FirstIndex 属性,返回在搜索字符串中匹配的位置。FirstIndex属性使用从零起算的偏移量,该偏移量是相对于搜索字符串的起始位置而言的。换言之,字符串中的第一个字符被标识为字符 0

  ' ○    Length 属性,返回在字符串搜索中找到的匹配的长度。

  ' ○    Value 属性,返回在一个搜索字符串中找到的匹配的值或文本。

  ' --------------------------------------------------------------

  ' Response.Write RegExpExecute("[ij]s.", "IS1 Js2 IS3 is4")

  Function RegExpExecute(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            '遍历匹配集合。

  RetStr = RetStr & "Match found at position "

  RetStr = RetStr & Match.FirstIndex & ". Match Value is '"

  RetStr = RetStr & Match.Value & "'." & "<BR>"

  Next

  RegExpExecute = RetStr

  End Function

  ' --------------------------------------------------------------------

  ' Replace 方法

  ' 替换在正则表达式查找中找到的文本。

  ' --------------------------------------------------------------------

  ' Response.Write RegExpReplace("fox", "cat") & "<BR>"        ' 将 'fox' 替换为 'cat'。

  ' Response.Write RegExpReplace("(S+)(s+)(S+)", "$3$2$1")    ' 交换词对.

  Function RegExpReplace(patrn, replStr)

  Dim regEx, str1                    ' 建立变量。

  str1 = "The quick brown fox jumped over the lazy dog."

  SET  regEx = New RegExp            ' 建立正则表达式。

  regEx.Pattern = patrn            ' 设置模式。

  regEx.IgnoreCase = True            ' 设置是否不区分大小写。

  RegExpReplace = regEx.Replace(str1, replStr)    ' 作替换。

  End Function

  ' --------------------------------------------------------------------

  ' 使用 Test 方法进行搜索。

  ' 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值

  ' 指示是否找到匹配的模式。正则表达式搜索的实际模式是通过 RegExp 对象的 Pattern 属性来设置的。

  ' RegExp.Global 属性对 Test 方法没有影响。

  ' 如果找到了匹配的模式,Test 方法返回 True;否则返回 False

  ' --------------------------------------------------------------------

  ' Response.Write RegExpTest("功能", "重要功能")

  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

  %>