0

我想实现一个算法/验证。如何确定一个字符串在 Flex 中是否包含超过 6 次的特定字符?

4

2 回答 2

2

有两种方法,我能想到:

  1. 像这样使用RegExp.replace()

    var ch:String = "a";    //Character, that must be checked
    var text:String = "This is an example to show how many times '"+ch+"' occured.";
    //Matches non-`ch` characters
    var regexp:RegExp = new RegExp("[^"+ch+"]","g");   
    //Replacing non-`ch` characters with empty string
    var timesOccured:Number = text.replace(regexp,"").length;  
    trace(text, ": " ,timesOccured );
    
  2. 像这样使用RegExp.match()

    var ch:String = "a";    //Character, that must be checked
    var text:String = "This is an example to show how many times '"+ch+"' occured.";
    //Matches `ch` characters
    var regexp:RegExp = new RegExp(ch,"g");
    var matches:Array = text.match(regexp);
    var timesOccured:Number = 0;
    //`matches` can be 'null', so we are performing additional check
    if( matches ){   
        timesOccured = matches.length;
    }
    trace(text, ": " ,timesOccured );
    

现在,当您拥有 时timesOccured,您可以轻松地进行验证:

if( timesOccured > 6 ){
   //Do some stuff
}else{
   //Do other stuff
}    

警告:如果您ch是正则表达式的特殊字符,如., +, (, ], \, 等...,您需要在将其传递给变量之前对其进行转义:regexp

ch = ch.replace(new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"), "\\$&");
于 2012-11-02T08:34:58.133 回答
2

正则表达式的更简单替代方法如下:

var str:String = "This is an example to show how many...";
//find occurrences for character 'a'

trace("Ocurrences:" + str.split('a').length-1);
于 2012-11-02T13:49:33.243 回答