`

Flex 正则表达式 字符串匹配 例子

    博客分类:
  • Flex
阅读更多

   var pattern:RegExp = /\w*sh\w*/gi;
   var str:String = "She sells seashells by the seashore";
   var result:Array = pattern.exec(str);
       
   while (result != null)
   {
       trace(result.index, "\t", pattern.lastIndex, "\t", result);
       result = pattern.exec(str);
   }

 

结果:

 

0 3 She

10 19 seashells

27 35 seashore

 

附:

 

http://help.adobe.com/zh_CN/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ea8.html

 

RegExp 类包含两个方法:exec()test()

除 RegExp 类的 exec()test() 方法外,String 类还包含以下方法,使您可以在字符串中匹配正则表达式:match()replace()search()splice()

 

test() 方法

RegExp 类的 test() 方法只检查提供的字符串是否包含正则表达式的匹配内容,如下面的示例所示:

var pattern:RegExp = /Class-\w/; 
var str = "Class-A"; 
trace(pattern.test(str)); // output: true

exec() 方法

RegExp 类的 exec() 方法检查提供的字符串是否有正则表达式的匹配,并返回具有如下内容的数组:

  • 匹配的子字符串

  • 同正则表达式中的任意括号组匹配的子字符串

该数组还包含 index 属性,此属性指明子字符串匹配起始的索引位置。

例如,请考虑使用以下代码:

var pattern:RegExp = /\d{3}\-\d{3}-\d{4}/; //U.S phone number 
var str:String = "phone: 415-555-1212"; 
var result:Array = pattern.exec(str); 
trace(result.index, " - ", result); 
// 7-415-555-1212

在正则表达式设置了 g (global) 标志时,多次使用 exec() 方法可以匹配多个子字符串:

var pattern:RegExp = /\w*sh\w*/gi; 
var str:String = "She sells seashells by the seashore"; 
var result:Array = pattern.exec(str); 
     
while (result != null) 
{ 
    trace(result.index, "\t", pattern.lastIndex, "\t", result); 
    result = pattern.exec(str); 
} 
//output:  
// 0      3      She 
// 10      19      seashells 
// 27      35      seashore

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics