match 메서드

정규식 패턴을 사용하여 문자열을 검색하고 그 결과를 배열로 반환합니다.

function match(rgExp : RegExp) : Array

인수

  • rgExp
    필수적 요소로서, 정규식 패턴 및 적용 가능한 플래그를 포함하는 Regular Expression 개체의 인스턴스입니다. 정규식 패턴과 플래그가 포함된 변수 이름이나 문자열 리터럴일 수도 있습니다.

설명

match 메서드가 일치하는 부분을 찾지 못하면 null을 반환합니다. match 메서드가 일치하는 부분을 찾으면 배열을 반환하고, 검색 결과를 반영하도록 RegExp 개체가 업데이트됩니다.

match 메서드가 반환하는 배열에는 input, indexlastIndex의 세 속성이 있습니다. input 속성은 전체 검색 문자열을 포함합니다. 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 개체

Regular Expression 개체

replace 메서드

search 메서드

test 메서드

개념

정규식 프로그래밍