RegExp對象詳解

JavaScript中的每個正則表達式都是一個對象,同其他的對象一樣。RegExp對象還有一些屬性,RegExp實例和構造函數都有屬性和方法。兩者的屬性在創建模式和進行測試的時候都會發生改變。
     (一) 實例屬性
      RegExp的實例有一些開發人員可以使用的屬性:
      global——Boolean值,表示g(全局選項)是否已設置。
      ignoreCase——Boolean值,表示i(忽然大小寫選項)是否已設置。
      lastIndex——整數,代表下次匹配將會從哪個字符位置開始(只有當使用exec()或test()函數纔會填入,否則爲0)。
  multiline——Boolean值,表示m(多行模式選項)是滯已設置。
  source——正則表達式的源字符串形式。例如,表達式/[ba]*/的source將返回*[ba]*。
  一般不會使用global、ignoreCase、multiline和source屬性,因爲一般之前就已知道了這些數據:

  var  reTest=/[ba]*/i;
  alert(reTest.global);      //outpus “false”
  alert(reTest.ignoreCase);  //outpus “true”
  alert(reTest.multiline);    //outpus “false”
  alert(reTest.source);      //outpus “[ba]*”
  真正有用的屬性是lastIndex,它可以告訴你正則表達式在某個字符串中停止之前,查找了多遠:
  var   sToMatch=”bbq is shrot for barbecue”;
  var   reB=/b/g;
  alert(reB.lastIndex);      //outpus “1”
  reB.exec(sToMatch);
  alert(reB.lastIndex);      //outpus “2”
  reB.exec(sToMatch);
  alert(reB.lastIndex);      //outpus “18”
  在這個例子中,正則表達式reB查找的是b。它當首次檢測sToMatch時,它發現在第一個位置——也就是位置0——是b;因此lastIndex屬性就被設置成1,而再次調用exec()時就從這個地方開始執行。再次調用exec(),表達式在位置1又發現了b,於是將lastIndex設置爲2。第三次調用時,發現b在位置17,於是又將lastIndex設置爲18。
   (二) 靜態屬性
    靜態的RegExp屬性對所有的正則表達式都有效。這些屬性也都與衆不同的,因爲它們都有兩個字句:一個複雜名字和一個以美元符號開關的簡短名字。下表中列出了這些屬性:
  這些屬性可以告訴你,關於剛使用exec()和test()完成的匹配的一些特定信息。例如:
  var  sToMatch=”this has been a short , short summer”;
  var  reShort=/(s)hort/g;
  reShort.test(sToMatch);
  alert(RegExp.input);
  alert(RegExp.leftContext);    //outputs “this has been a short,short summer”
  alert(RegExp.rightContext);   //outputs “this has been a”
  alert(RegExp.lastMatch);     //outputs “,short summer”
  alert(RegExp.lastMatch);     //outputs “short”
  alert(RegExp.lastParen);      //outputs “s”
  這一個例子描述了幾個不販屬性應該如何使用:
  input屬性總是等於測試用的字符串。
  RegExp.leftContext包含第一個實例 “short”之前的所有字符,同時RegExp.rightContext包含第一個實例”short”之後的所有字符。
  lastMatch的屬性包含最後匹配整個正則表達式的字符串,這裏就是”short”。
  lastParen屬性包含最後匹配的分組,這裏就是”s”。
  也可以使用這些屬性的短名字,不過對其中的大部分必須使用方括號標記,因有這些名字在ECMAScript的語法中是不合法的。
  var  sToMatch=”this has been a short, short summer”;
  var  reShort=/(s)hort/g;
  reShort.test(sToMatch);
  alert(RegExp.$_);     //outputs “this has been a short, short summer”
  alert(RegExp.[“$`”]);   //outputs “this has been a”
  alert(RegExp.[“$’”]);   //outputs “, short summer”
  alert(RegExp.[“$&”]);  //outputs “short”
  alert(RegExp.[“$+”]);  //outputs “s”
  每次執行exec()和test()時,所有的屬性(除multiline外)都會被重新設置。multiline屬性在這裏不同於其他屬性,因爲它不依賴最後一次執行的匹配。相反,它可以設置所有的正則表達式的m選項。
  var  sToMatch=”First second\nthird fourth\nfifth sisxth”
  var  reLastWordOnLine=/(\w+)$/g;
  RegExp.multiline=true;
  var  arrWords=sToMatch.match(reLastWordOnLine);
  這段代碼執行結束後,arrWords包含”second”,”fourth”和”sisth”,就像m選項已在表達式中設置過一樣。

發佈了6 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章