match 方法

利用規則運算式 (Regular Expression) 模式執行字串搜尋,然後傳回包含搜尋結果的陣列。

function match(rgExp : RegExp) : Array

引數

  • rgExp
    必要項。 包含有規則運算式模式和適用旗標的規則運算式物件的執行個體。 也可以是包含規則運算式模式與適用旗標的變數名稱或字串常值。

備註

如果 match 方法找不到符合的項目,會傳回 null。 如果找到符合的項目,則 match 方法會傳回一個陣列,然後更新全域 RegExp 物件的屬性來反映符合的結果。

match 方法傳回的陣列有三種屬性:inputindexlastIndexinput 屬性包含整個所搜尋的字串。 index 屬性包含了在整個所搜尋字串中相符子字串的位置。 lastIndex 屬性則包含了最後相符項目中跟著最後一個字元的位置。

如果未設定全域旗標 (g),陣列的元素 0 會包含整個相符項目,而元素 1 至 n 則會含在相符項目中出現的任何子項目。 沒有在該方法上設定全域旗標時,這項行為與 exec 方法 的行為相同。 如果設定全域旗標,元素 0 至 n 就會包含所有的相符項目。

範例

下列範例會說明未設定全域旗標 (g) 時, match 方法的使用方式。

var src = "Please send mail to george@contoso.com and someone@example.com. Thanks!";

// Create a regular expression to search for an e-mail address.
// The global flag is not included.
// (More sophisticated RegExp patterns are available for
// matching an e-mail address.)
var re = /(\w+)@(\w+)\.(\w+)/;

var result = src.match(re);

// Because the global flag is not included, the entire match is
// in array element 0, and the submatches are in elements 1 through n.
print(result[0]);
for (var index = 1; index < result.length; index++)
{
    print("submatch " + index + ": " + result[index]);
}

// Output:
//  george@contoso.com
//  submatch 1: george
//  submatch 2: contoso
//  submatch 3: com

此範例說明在設定全域旗標 (g) 時,match 方法的使用。

var src = "Please send mail to george@contoso.com and someone@example.com. Thanks!";

// Create a regular expression to search for an e-mail address.
// The global flag is included.
var re = /(\w+)@(\w+)\.(\w+)/g;

var result = src.match(re);

// Because the global flag is included, the matches are in
// array elements 0 through n.
for (var index = 0; index < result.length; index++)
{
    print(result[index]);
}

// Output:
//  george@contoso.com
//  someone@example.com

下列程式碼說明如何使用 match 方法來搜尋字串常值。

var re = /th/i;
var result = "through the pages of this book".match(re);

需求

版本 3

套用至︰

String 物件

請參閱

參考

exec 方法

RegExp 物件

規則運算式物件

replace 方法

search 方法

test 方法

概念

規則運算式程式設計