Flash AS3 RegExp

时间:2016-09-05 18:57:29

标签: regex string actionscript-3 flash

我不知道我是否可以使用RegExp对象来获得我想要的结果,如下所示: 我想测试一个与correctAnswer变量的一部分匹配的答案(不区分大小写)但排除任何未包含在correctAnswer变量中的其他世界。

是否可以使用RegExp以避免模式中未包含的任何单词?

var correctAnswer:String = "Hello Dummy World";
var answer1:String = "hello world"; //should be a good answer
var answer2:String = "Hello dummy world"; //should be a good answer
var answer3:String = "Hello WRONG world";  //should be a wrong answer
var answer4:String = "Another String here";  //should be a wrong answer
function checkAnswer(a:String):String{
    var exp1:RegExp=/Hello|Dummy|World/ig;
    var r= a.replace(exp1,"OK");
    trace(a.search(exp1));
    return r
}
trace(checkAnswer(answer1)); // this should return "Hello Dummy World"
trace(checkAnswer(answer2)); // this should return "Hello Dummy World"
trace(checkAnswer(answer3)); // this should throw a wrong answer
trace(checkAnswer(answer4)); // this should throw a wrong answer

现在输出给了我:

0
OK OK // in place of "Hello Dummy World"
0
OK OK OK // in place of "Hello Dummy World"
0
OK WRONG OK // in place of "bad answer"
-1
Another String here // in place of "bad answer"

对不起我的英语,如果你能给我一些意见/建议或可能的答案,谢谢你。

在这种情况下,我可能不应该使用RegExp对象? 我对此并不熟悉,但如果这可能有用,这可能比条件循环测试所有可能的情况最好???

我在这里有点困惑,希望能清楚地描述这个问题。

谢谢。

1 个答案:

答案 0 :(得分:2)

以下代码将提取正确答案中的所有“单词”并删除指定字符串中的任何出现,以便在修剪后不会留下任何不受欢迎的内容!

var correctAnswer:String = "Hello Dummy World";

var answer1:String = "hello world"; // Should be a good answer
var answer2:String = "Hello dummy world"; // Should be a good answer
var answer3:String = "Hello WRONG world";  // Should be a wrong answer
var answer4:String = "Another String here";  // Should be a wrong answer

var tokenized:Array = correctAnswer.split(" ");
function checkAnswer(a:String):Boolean{
    var exp:RegExp = new RegExp(tokenized.join("|"), "ig");
    var correctKeywordsRemoved:String = a.replace(exp, "");
    var isCorrect:Boolean = trim(correctKeywordsRemoved).length == 0;
    trace("Your answer of '"+a+"' is "+(isCorrect ? "CORRECT :)" : "WRONG :("));
    return isCorrect;

    function trim(s:String):String {
        return s.replace(/^\s*|\s*$/gim, "");
    }
}

checkAnswer(answer1); // Your answer of 'hello world' is CORRECT :)
checkAnswer(answer2); // Your answer of 'Hello dummy world' is CORRECT :)
checkAnswer(answer3); // Your answer of 'Hello WRONG world' is WRONG :(
checkAnswer(answer4); // Your answer of 'Another String here' is WRONG :(