正 文

正则表达式快速入门教程


www.7dspace.com  更新日期:2005-10-21 1:30:30  七度空间


  学习了这三个对象和集合,如何应用于字符串的判断和替换呢?regExp对象的三个方法正好解决了这个问题,它们是Replace方法、Test方法和Execute方法。

  1、Replace 方法

  替换在正则表达式查找中找到的文本。我们还是先看个例子:下面的例子说明了 Replace 方法的用法。

<%
 Function ReplaceTest(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 ’ 设置是否区分大小写。
  ReplaceTest = regEx.Replace(str1, replStr) ’ 作替换。
 End Function
 Response.write ReplaceTest("fox", "cat") & "<BR>" ’ 将 ’fox’ 替换为 ’cat’。
 Response.write ReplaceTest("(\S+)(\s+)(\S+)", "$3$2$1") ’ 交换词对.
%>

  2、Test 方法

  对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。正则表达式搜索的实际模式是通过RegExp对象的Pattern属性来设置的。RegExp.Global属性对Test方法没有影响。

  如果找到了匹配的模式,Test方法返回True;否则返回False。下面的代码说明了Test 方法的用法。

<%
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
Response.write RegExpTest("is.", "IS1 is2 IS3 is4")
%>

  3、Execute 方法

  对指定的字符串执行正则表达式搜索。正则表达式搜索的设计模式是通过 RegExp 对象的 Pattern 来设置的。

  Execute 方法返回一个 Matches 集合,其中包含了在 string 中找到的每一个匹配的 Match 对象。如果未找到匹配,Execute 将返回空的 Matches 集合。

  在JavaScript 1.2版以后,JavaScript也支持正则表达式。

  1、replace

  replace在一个字符串中通过正则表达式查找替换相应的内容。replace并不改变原来的字符串,只是重新生成了一个新的字符串。如果需要执行全局查找或忽略大小写,那么在正则表达式的最后添加g和i。

  例:

<SCRIPT>
 re = /apples/gi;
 str = "Apples are round, and apples are juicy.";
 newstr=str.replace(re, "oranges");
 document.write(newstr)
</SCRIPT>

  结果是:"oranges are round, and oranges are juicy."

  例:

<SCRIPT>
str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
document.write(newstr)
</SCRIPT>

  结果是:"Twas the night before Christmas..."

  例:

<SCRIPT>
re = /(\w+)\s(\w+)/;str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>

  结果是:"Smith, John".

6页,页码:[1] [2] [3] [4] [5] [6] 

上一篇:Windows XP SP2中实现双人终端登陆
下一篇:Java的垃圾回收机制详解和调优
作者:baggio785  来源:blog ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐