Share via


정규식 프로그래밍

JScript의 정규식을 사용하여 문자열의 패턴을 검색하고, 텍스트를 바꾸고, 부분 문자열을 추출할 수 있습니다.

검색

다음 JScript 예제에서는 특정 단어의 모든 항목을 찾습니다.

이 정규식을 만드는 문은 다음과 같습니다.

var re = /\w+/g;

/\w+/ 패턴은 A-Z, a-z, 0-9, 밑줄 등의 문자를 하나 이상 찾도록 지정합니다. 이 패턴 뒤에 오는 g(전역) 플래그는 패턴의 첫 번째 항목이 아니라 패턴의 모든 항목을 찾도록 지정합니다.

또한 다음과 같은 대체 JScript 구문을 사용할 수도 있습니다.

var re = new RegExp("\\w+", "g");

각 일치 항목을 검색하기 위해 exec 메서드는 null이 반환될 때까지 lastIndex 위치부터 검색을 유지합니다.

function SearchGlobal()
{
    var src = "The quick brown fox jumps over the lazy dog.";

    // Create a regular expression pattern that has a global flag.
    var re = /\w+/g;

    var result;

    // Get the first match.
    result = re.exec(src);
    while (result != null)
    {
        print (result.index + "-" + result.lastIndex + "\t" + result[0]);

        // Get the next match.
        // Because the global flag is set, the search starts at the
        // position of lastIndex.
        result = re.exec(src);
    }

    // Output:
    //  0-3 The
    //  4-9 quick
    //  10-15 brown
    //  16-19 fox
    //  20-25 jumps
    //  26-30 over
    //  31-34 the
    //  35-39 lazy
    //  40-43 dog
}

다음 예제에서는 첫 번째 일치 항목만 찾습니다. 전역(g) 플래그가 설정되지 않았기 때문에 검색은 검색 문자열의 시작 부분에서 시작됩니다.

function SearchNonGlobal()
{
    var src = "The quick brown fox jumps over the lazy dog.";

    // Create a regular expression that does not have
    // a global flag.
    var re = /\w+/;

    // Get the first match.
    // Because the global flag is not set, the search starts
    // from the beginning of the string.
    var result = re.exec(src);

    if (result == null)
        print ("not found");
    else
        {   
        print (result.index + "-" + result.lastIndex + "\t" + result[0]);
        }

    // Output:
    //  0-3 The
}

대체

다음 예제에서는 "the" 항목을 "a"로 바뀝니다. 정규식 플래그에 i(대/소문자 구분 안 함) 플래그가 포함되어 있지 않기 때문에 "The" 항목은 바뀌지 않습니다.

이 예제에서는 replace 메서드를 사용합니다.

function ReplaceGlobal()
{
    var src = "The batter hit the ball with the bat ";
    src += "and the fielder caught the ball with the glove.";

    // Replace "the" with "a".
    var re = /the/g;
    var result = src.replace(re, "a");

    print(result);

    // Output:
    //  The batter hit a ball with a bat and a fielder caught a ball with a glove.
}

부분 문자열 추출

정규식 패턴에 괄호를 추가하면 나중에 사용하기 위해 저장할 수 있는 부분 문자열이 만들어집니다.

다음 예제의 패턴에는 세 개의 부분 일치 문자열이 포함됩니다. 부분 일치 문자열은 각 일치 문자열과 함께 표시됩니다.

exec 메서드는 배열을 반환합니다. 이 배열의 0 요소에는 전체 일치 문자열이 포함되고 1부터 n 요소에는 부분 일치 문자열이 포함됩니다.

function SearchWithSubmatches()
{
    var result;

    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.
    // Include the global flag.
    // (More sophisticated RegExp patterns are available for
    // matching an e-mail address.)
    var re = /(\w+)@(\w+)\.(\w+)/g;

    // Get the first match.
    result = re.exec(src);
    while (result != null)
    {
        print ("e-mail address: " + result[0]);

        // Get the submatched parts of the address.
        print ("user name: " + result[1]);
        print ("host name: " + result[2]);
        print ("top-level domain: " + result[3]);
        print ("");

        // Get the next match.
        result = re.exec(src);
    }

    // Output:
    //  e-mail address: george@contoso.com
    //  user name: george
    //  host name: contoso
    //  top-level domain: com

    //  e-mail address: someone@example.com
    //  user name: someone
    //  host name: example
    //  top-level domain: com
}

Flags

JScript 정규식 /abc/gim에서 g는 전역 플래그를 지정하고, i는 대/소문자 구분 안 함 플래그를 지정하며, m은 여러 줄 플래그를 지정합니다.

다음 표에서는 허용된 플래그를 보여 줍니다.

JScript 플래그

플래그가 있는 경우

g

검색된 문자열에서 패턴의 첫 번째 항목이 아니라 패턴의 모든 항목을 찾습니다.

i

검색에서 대/소문자를 구분하지 않습니다.

m

^ 문자는 \n 또는 \r 뒤에 있는 위치를 찾습니다.

$ 문자는 \n 또는 \r 앞에 있는 위치를 찾습니다.

이 플래그가 있는지 여부에 상관없이 ^ 문자는 검색된 문자열의 시작 부분에 있는 위치를 찾고 $ 문자는 검색된 문자열의 끝 부분에 있는 위치를 찾습니다.

추가 기능

다음과 같은 프로그래밍 기능을 추가로 사용할 수 있습니다.

기능

설명

compile 메서드(Visual Studio - JScript)

빠른 실행을 위해 정규식을 내부 형식으로 컴파일합니다.

test 메서드

검색된 문자열에서 패턴이 발생하는지 여부를 테스트합니다.

search 메서드

첫 번째 일치 항목의 위치를 반환합니다.

참고 항목

참조

Regular Expression 개체

개념

정규식 만들기

정규식 구문