搭配字串使用規則運算式的方法

RegExp 類別包含兩種方法:exec()test()

除了 RegExp 類別的 exec()test() 方法外,String 類別也包含下列方法,讓您符合字串中的規則運算式:match()replace()search()splice()

副主題

test() 方法
exec() 方法
使用 RegExp 參數的 String 方法

test() 方法

RegExp 的 test() 方法只會檢查所提供的字串是否包含規則運算式的相符項目,如下列範例所示:

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

exec() 方法

RegExp 類別的 exec() 方法會檢查對規則運算式相符項目所提供的字串,並傳回帶有下列項目的陣列:

陣列也包含 index 屬性,指出子字串相符項目開頭的索引位置。

例如,請考慮下列程式碼:

var pattern:RegExp = /\d{3}\-\d{3}-\d{4}/; //美國電話號碼
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);
}
// 輸出:
// 0      3      She
// 10      19      seashells
// 27      35      seashore

使用 RegExp 參數的 String 方法

下列 String 類別的方法將規則運算式當做參數使用:match()replace() search()split()。如需有關這些方法的詳細資訊,請參閱尋找字串中的樣式並取代子字串


Flash CS3

 

有新的意見加入至這個頁面時,傳送電子郵件給我 | 意見報告

目前頁面: http://livedocs.adobe.com/flash/9.0_tw/main/00000120.html