四步讲解ASP中正则表达式的应用

作者:  日期:2007-5-3 16:20:18  来源:  点击:次  评论

  三、JavaScript中正则表达式的使用

  在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".

  2、search

  search通过正则表达式查找相应的字符串,只是判断有无匹配的字符串。如果查找成功,search返回匹配串的位置,否则返回-1。

  

         search(regexp)

  <SCRIPT>

  function testinput(re, str){

  if (str.search(re) != -1)

  midstring = " contains ";

  else

  midstring = " does not contain ";

  document.write (str + midstring + re.source);

  }

  testinput(/^[1-9]/i,"123")

  </SCRIPT>

  3、match

  match方法执行全局查找,查找结果存放在一个数组里。

  例一:

  <SCRIPT>

  str = "For more information, see Chapter 3.4.5.1";

  re = /(chapter d+(.d)*)/i;

  found = str.match(re);

  document.write(found);

  </SCRIPT>

  显示结果:Chapter 3.4.5.1,Chapter 3.4.5.1,.1

  例二:

  <SCRIPT>

  str = "abcDdcba";

  newArray = str.match(/d/gi);

  document.write(newArray);

  </SCRIPT>

  显示结果D, d.

本新闻共4页,当前在第3页  1  2  3  4  

〖责任编辑:寅生〗 发送给好友 打印 顶部

推荐教程

热点教程

请尊重别人的劳动,原创教程转载必须注明作者及出处
中国教程网简介 | 业务合作 | 广告服务 | 联系我们 | 招聘信息 | English | 网站地图 | 客服中心

中国教程网
©2005-2007