2015-10-25 35 views
1

我正在开发一个涉及创建Adobe Flash应用程序的项目,该应用程序可以更改输入文本框中文本的时态。 最初的例子是: “亚特兰蒂斯的城市迷路了,狼人应该受到指责,我很伤心,我的朋友也很难过,居民和亚特兰蒂斯人也不高兴,这真是太浪费了。Actionscript 3使用正则表达式替换字符串中的单词

我已经想出了如何使它过去式和现在式。但我似乎无法弄清楚如何将“我是”的部分从过去时改回现在时(我是)。请帮忙。

original_btn.addEventListener(MouseEvent.CLICK, ConvertOriginal); 
    past_btn.addEventListener(MouseEvent.CLICK, ConvertPast); 
    present_btn.addEventListener(MouseEvent.CLICK, ConvertPresent); 

    function ConvertOriginal(e:MouseEvent):void { 
     body_txt.text = "The city of Atlantis is lost. The werewolves were to blame. I am saddened and so were my friends. The residents and Atlantis are unhappy too. It is such a waste."; 
} 
    function ConvertPast(e:MouseEvent):void { 
     var myPattern1:RegExp = /\s(is|am)\s/g; 
     var str:String = body_txt.text; 
     body_txt.text = body_txt.text.replace(myPattern1, " was "); 
     var myPattern2:RegExp = /\sare\s/g; 
     body_txt.text = body_txt.text.replace(myPattern2, " were "); 
} 
    function ConvertPresent(e:MouseEvent):void { 
     var myPattern1:RegExp = /\swas\s/g; 
     var str:String = body_txt.text; 
     body_txt.text = body_txt.text.replace(myPattern1, " is "); 
     var myPattern2:RegExp = /was/g; 
     body_txt.text = body_txt.text.replace(myPattern2, " I am "); 
     var myPattern3:RegExp = /\swere\s/g; 
     body_txt.text = body_txt.text.replace(myPattern3, " are "); 
} 
+0

使用单词边界'\ B',而不是'\ s'和更换部件,你不不需要添加空格。 –

+0

谢谢Avinash Raj。但是,如何改变“我是”回到“我是”。因为\ bwas \ b被替换为“is” – Alisa

+0

,所以我一直得到“我是”,对不起,我在语法部分非常虚弱。 –

回答

0

你需要使用正则表达式替换的顺序是:与is

  • \bwere\b

    1. \bI was\bI am
    2. \bwas\bare

    这里是你的modifie d功能:

    function ConvertPresent(e:MouseEvent):void { 
        var myPattern1:RegExp = /\bI was\b/g; 
        var str:String = body_txt.text; 
        body_txt.text = body_txt.text.replace(myPattern1, "I am"); 
        var myPattern2:RegExp = /\bwas\b/g; 
        body_txt.text = body_txt.text.replace(myPattern2, "is"); 
        var myPattern3:RegExp = /\bwere\b/g; 
        body_txt.text = body_txt.text.replace(myPattern3, "are"); 
    } 
    
  • 0

    您可以使用字符串替换方法,将它,像这样

    private function replaceAll(pattern:*,replacementStr:String,originalString:String):String { 
         if (originalString!= null) { 
          while (originalString.search(pattern) != -1) { 
           originalString= originalString.replace(pattern,replacementStr); 
          } 
         } 
         return originalString; 
        }