Forum und email

패턴 문법

(No version information available, might be only in CVS)

패턴 문법 — PCRE 정규표현식 문법 설명

설명

PCRE 라이브러리는 아주 약간의 차이(아래를 참고)를 제외하고, 펄 5와 동일한 구문과 의미를 사용하여 정규표현식 패턴 매칭을 수행하는 함수의 집합입니다. 현재 수행은 펄 5.005에 대응합니다.

펄과의 차이

여기에서 설명한 차이는 펄 5.005 기준입니다.

  1. PCRE는 다른 문자 집합으로 컴파일할 수 있지만, 기본적으로 공백 문자는 C 라이브러리 함수 isspace()가 인식하는 모든 문자입니다. 보통 isspace()는 스페이스, 폼피드, 줄바꿈, 캐리지 리턴, 수평 탭, 수직 탭을 인식합니다. 펄 5는 공백 문자에 수직 탭을 포함하지 않습니다. 오랜 기간동안 펄 문서의 \v 이스케이프는 사실상 인정되지 않았습니다. 그러나 문자 자체는 적어도 5.002까지 공백으로 취급되었으며, 5.004와 5.005는 \s에서 인식하지 않습니다.
  2. PCRE는 lookahead 단정에서 반복 횟수를 허용하지 않습니다. 펄은 허용하지만, 생각하는 그대로의 의미를 갖지 않습니다. 예를 들어, (?!a){3}는 다음 세 문자가 "a"가 아닌 것을 의미하지 않습니다. 단지, 다음 문자가 "a"가 아니라는 것을 세번 확인할 뿐입니다.
  3. 부정 lookahead 단정 안에서 일어나는 서브패턴 검출을 카운트를 하지만, 시작 위치 벡터에 그 엔트리를 설정하지는 않습니다. 펄은 부정 lookahead 단정이 단 하나의 브랜치를 가지고 있을 경우에 한하여, 그 단정이 매치에 실패(결과적으로 성공)하기 전에 매치한 어떠한 패턴에 대해서만 그에 대한 숫자 변수를 설정합니다.
  4. 바이너리 제로 문자는 목표 문자열에서는 지원하지만, 패턴 문자열에서는 허용하지 않습니다. 패턴은 제로로 종료하는 보통의 C 문자열로 처리하기 때문입니다. 패턴에서 바이너리 제로를 표현하기 위해서는 이스케이프 시퀀스 "\\x00"로 사용할 수 있습니다.
  5. 다음의 펄 이스케이프 시퀀스는 지원하지 않습니다: \l, \u, \L, \U, \E, \Q. 사실, 이들은 펄의 일반 문자열 핸들링이며, 패턴 매칭 엔진의 부분이 아닙니다.
  6. 펄의 \G는 싱글 패턴 매치에 적절하지 않기 때문에 지원하지 않습니다.
  7. 당연하게도, PCRE는 (?{code}) 구조를 지원하지 않습니다.
  8. 패턴의 일부가 반복될 때, 잡아낸 문자열의 설정에 관해서, 펄 5.005_02에서 일부 이상한 동작이 존재합니다. 예를 들어, "aba"에 대해서 패턴 /^(a(b)?)+$/를 매칭하면 $2를 "b" 값으로 설정하지만, "aabbaa"에 대해서 /^(aa(bb)?)+$/를 매칭하면 $2를 설정하지 않습니다. 하지만 패턴을 /^(aa(b(b))?)+$/로 변경하면 $2(와 $3)를 설정합니다. 펄 5.004에서는 $2를 두 경우 모두 설정했으며, PCRE에서도 TRUE입니다. 앞으로 펄이 이 차이를 일관성 있게 변경한다면, PCRE는 그 변경에 따를 것입니다.
  9. 또다른 해결되지 않은 모순점은 펄 5.005_02가 패턴 /^(a)?(?(1)a|b)+$/를 문자열 "a"에 매치하지만, PCRE는 하지 않습니다. 그러나 펄과 PCRE 모두 /^(a)?a/를 "a"에 매치하고 $1을 설정하지 않습니다.
  10. PCRE는 펄 정규표현식 기능의 몇가지 확장을 지원합니다:

    1. lookbehind 단정은 고정 길이 문자열에만 매치해야하지만, 양자 택일의 lookbehind 단정에서는 다른 길이의 문자열을 매치할 수 있습니다. 펄 5.005에서는 모두 같은 길이를 가질 것을 요구합니다.
    2. PCRE_DOLLAR_ENDONLY를 설정하고 PCRE_MULTILINE를 설정하지 않으면 $ 메타 문자는 문자열의 가장 마지막에만 매치합니다.
    3. PCRE_EXTRA를 설정하면, 백슬래쉬 뒤에 특별한 의미를 가지지 않는 문자의 사용은 실패하게 됩니다.
    4. PCRE_UNGREEDY를 설정하면, 반복 수량어의 greediness가 뒤집어져서, 기본값으로 greedy하지 않게 됩니다. 하지만 뒤에 물음표가 붙으면 greedy하게 됩니다.

정규표현식 상세

소개

아래 설명은 PCRE가 지원하는 정규표현식의 문법과 의미입니다. 정규표현식은 펄 문서 및 많은 책들에 설명이 있으며, 그 중 일부에는 풍부한 예제를 가지고 있습니다. O'Reilly에서 출판한 Jeffrey Friedl의 "Mastering Regular Expressions"(ISBN 1-56592-257-3)는 예제들을 매우 자세하게 다루고 있습니다. 여기의 설명은 레퍼런스 문서에 따릅니다.

정규표현식은 주어진 문자열에 대하여 왼쪽에서 오른쪽으로 매치하는 패턴입니다. 문자열은 패턴으로 준비하고, 목표에서 대응하는 문자열에 매치합니다. 간단한 예로, 패턴 The quick brown fox는 목표 문자열의 동일한 부분에 매치합니다.

메타 문자

정규표현식이 강력한 이유는 패턴에 선택과 반복을 포함할 수 있다는 점입니다. 이는 특별한 방법으로 해석하는 메타 문자를 사용하여 패턴에 넣습니다.

메타 문자는 두가지 종류가 존재합니다: 대괄호 안을 제외하고 패턴의 어디에서라도 작동하는 종류와, 대괄호 안에서만 작동하는 종류입니다. 다음은 대괄호 밖에서 사용하는 메타 문자들입니다.

\
여러가지로 사용하는 일반적인 이스케이프 문자
^
목표의 처음 (멀티라인 모드에서는 줄의 처음)
$
목표의 마지막 (멀티라인 모드에서는 줄의 끝)
.
(기본값으로) 줄바꿈을 제외한 아무 문자
[
클래스 정의 시작 문자
]
클래스 정의 끝 문자
|
선택 브랜치 시작
(
서브패턴 시작
)
서브패턴 끝
?
( 의미 확장, 또는 0회나 1회, 또는 수량어 minimizer
*
0회 이상의 횟수
+
1회 이상의 횟수
{
최소/최대 횟수 시작
}
최소/최대 횟수 끝
대괄호 안쪽의 패턴은 "문자 클래스"라고 부릅니다. 다음은 문자 클래스에서 사용하는 메타 문자들입니다:
\
일반적인 이스케이프 문자
^
처음 문자로 올 때, 부정 클래스로 설정
-
문자 범위 지정
]
문자 클래스 종료
다음 섹션은 각 메타 문자의 사용을 설명합니다.

백슬래쉬

백슬래쉬 문자는 여러가지 사용법을 가집니다. 먼저, 뒤에 영숫자가 아닌 문자가 붙는다면, 그 문자가 가지고 있는 특별한 의미가 사라집니다. 이러한 이스케이프 문자로 백슬래쉬를 사용하는 것은 문자 클래스 안과 밖 양쪽에 모두 적용됩니다.

예를 들어, "*" 문자를 매치하길 원한다면, 패턴에는 "\*"로 써야합니다. 이는 따라오는 문자가 메타 문자이던 아니던간에 관계 없이 적용하기 떄문에, 영숫자가 아닌 문자에 그 자체를 사용하기 위해 "\"를 붙이는 것이 항상 안전합니다. 특히, 백슬래쉬를 매치하고자 한다면, "\\"로 써야합니다.

패턴에 PCRE_EXTENDED 옵션을 사용하면, 패턴에 존재하는 (문자 클래스 안이 아닌) 공백, 그리고 문자 클래스 밖의 "#"사이의 문자와 바로 뒤의 줄바꿈 문자를 무시합니다. 이스케이프하는 백슬래쉬를 공백이나 "#"문자를 패턴에 넣기 위해 사용할 수 있습니다.

백슬래쉬의 두번째 사용법은 패턴에서 출력할 수 없는 문자를 보여지게 인코딩하는 방법을 제공합니다. 바이너리 제로가 패턴 종료를 의미하는걸 제외하면, 출력할 수 없는 문자가 나타나는 제한은 존재하지 않습니다. 그러나 패턴을 텍스트 편집으로 준비할 때는, 다음의 이스케이프 시퀀스를 사용하는 편이 바이너리 문자를 직접 표현하는 것보다 간편합니다:

\a
알람, BEL 문자(hex 07)
\cx
"control-x", x는 임의의 문자
\e
이스케이프 (hex 1B)
\f
폼피드 (hex 0C)
\n
줄바꿈 (hex 0A)
\r
캐리지 리턴 (hex 0D)
\t
탭 (hex 09)
\xhh
16진 코드 hh 문자
\ddd
8진 코드 ddd 문자, 혹은 역참조

"\cx"의 효과는 다음과 같이 계산합니다: "x"가 소문자라면, 대문자로 변환합니다. 그 후, 문자의 6번째 비트(hex 40)가 뒤집어집니다. 즉 "\cz"은 hex 1A가 되고, "\c{"은 hex 3B, 그리고 "\c;"은 hex 7B가 됩니다.

"\x" 뒤에, 두개의 16진 숫자를 읽습니다. (대소문자는 구별하지 않습니다)

"\0"은 다음의 두자리의 8진수를 읽습니다. 양쪽 모두, 두자리가 되지 않을 경우, 그 표현을 그대로 사용합니다. 즉 "\0\x\07" 시퀀스는 두개의 바이너리 제로에 이어지는 BEL 문자를 정의합니다. 바로 뒤에 8진수로 인식되는 문자가 이어질 경우에는 처음의 제로 뒤에 두자리 수를 써야한다는 것을 잊지 마십시오.

백슬래쉬 뒤에 0이 아닌 수가 올 경우에 혼동할 수 있습니다. 문자 클래스 밖에서, PCRE는 그것과 따라오는 수를 10진수로 읽습니다. 수가 10보다 작거나, 표현식에서 수 이상의 묶음을 잡아냈다면, 이 시퀀스는 역참조가 됩니다. 이 작동에 관해서는 아래에, 묶음 서브패턴에 설명이 있습니다.

문자 클래스 안이나, 10진수 9 이상이 없고 서브패턴이 그만큼 존재하지 않을 경우, PCRE는 백슬래쉬 뒤의 세자리 8진수로 다시 읽어들여, 해당하는 8비트 값으로 하나의 바이트를 생성합니다. 어떠한 수라도 사용할 수 있습니다. 예를 들면:

\040
스페이스의 다른 표현 방법
\40
40개 미만의 서브 패턴을 검출하였을때, 동일한 의미
\7
항상 역참조
\11
역참조, 혹은 탭의 다른 표현 방법
\011
항상 탭
\0113
문자 "3"이 따라오는 탭
\113
8진 코드 113 문자 (역참조는 99까지입니다)
\377
1비트만을 제외한 바이트
\81
역참조이거나 "8"과 "1"의 두 문자가 붙는 바이너리 제로

100이상의 8진 값은 앞에 제로가 붙지 않아야만 합니다. 세자리를 넘어가는 8진 값은 읽지 않습니다.

하나의 바이트값을 정의하는 모든 시퀀스는 문자 클래스 내외, 어디에서도 사용할 수 있습니다. 추가로, 문자 클래스 안에서 "\b" 시퀀스는 백스페이스 문자(hex 08)로 해석합니다. 문자 클래스 밖에서는 다른 의미를 가집니다. (아래를 참고)

백슬래쉬의 세번째 사용법은 일반적인 문자 타입의 지정입니다:

\d
임의의 10진 숫자
\D
10진 숫자가 아닌 임의의 문자
\s
임의의 공백 문자
\S
공백이 아닌 임의의 문자
\w
임의의 "word" 문자
\W
임의의 "non-word" 문자

각 이스케이프 시퀀스 조합은 완전한 문자 세트를 두개의 개별 세트로 분리합니다. 주어진 문자는 각 조합의 한쪽에만 매치합니다.

"word" 문자는 어떠한 문자나 숫자, 혹은 언더스코어(_)입니다. 즉, 펄의 "word"에 해당하는 어떠한 문자입니다. 문자와 숫자의 정의는 PCRE의 문자 테이블이 제어하고, 로케일 특정 매칭이 존재할 경우에는 다양할 수 있습니다. (위쪽의 "로케일 지원" 참고) 예를 들어, "fr"(프랑스어) 로케일에서는, 128 이상의 몇몇 코드를 엑센트 문자를 나타내는데 사용하며, 이들은 \w에 매치합니다.

문자형 시퀀스는 문자 클래스 안과 밖에서 모두 사용할 수 있습니다. 각각 해당하는 형의 한 문자에 매치합니다. 현재 매칭 위치가 목표 문자열의 마지막이라면, 전부 실패하고, 어떠한 문자도 매치하지 않습니다.

백슬래쉬의 네번째 사용법은 간단한 단정입니다. 단정은 조건이 목표 문자열에서 다른 부분에 매치하지 않고, 특정한 위치에만 매치하도록 지정합니다. 복잡한 단정을 위한 서브패턴의 사용법은 아래에 설명이 있습니다. 백슬래쉬 단정은 다음과 같습니다.

\b
word 경계
\B
word 경계가 아님
\A
목표의 처음 (멀티라인 모드와 무관)
\Z
목표의 마지막이나 마지막에서 줄바꿈 (멀티라인 모드와 무관)
\z
목표의 마지막 (멀티라인 모드와 무관)

단정은 문자 클래스 안에서 사용할 수 없습니다. ("\b"가 문자 클래스 안에서는 백스페이스 문자를 나타내는 점에 주의하십시오)

word 경계는 현재 문자와 이전 문자가 둘 다 \w에 매치하지 않거나 둘 다 \W에 매치하지 않는 (즉, 하나는 \w에 매치하고 다른 하나는 \W에 매치) 목표 문자열의 위치이거나, 처음이나 마지막 문자가 \w에 매치할 경우는 문자열의 처음이나 마지막입니다.

\A, \Z, \z 단정은 전통적인 circumflex와 달러와는 달리 옵션과 관계 없이 목표 문자열의 가장 처음이나 가장 마지막에만 매치합니다. 이들은 PCRE_MULTILINE이나 PCRE_DOLLAR_ENDONLU 옵션에 영향을 받지 않습니다. \Z\z의 차이는, \Z가 문자열의 마지막뿐만 아니라 문자열 마지막 문자가 줄바꿈일 경우에는 바로 앞에도 매치하지만, \z는 마지막에만 매치합니다.

Circumflex와 달러

문자열 클래스의 밖, 기본 매칭 모드에서는 circumflex 문자는 현재 매칭 위치가 목표 문자열의 시작일 경우에만 성공하는 단정입니다. 문자열 클래스 안에서 cicumflex는 완전히 다른 의미를 가집니다. (아래 참고)

여러 개의 선택을 가질 경우 circumflex는 패턴의 처음 문자일 필요가 없지만, 패턴이 그 브랜치에 처음 매치할 경우를 나타내는 각 선택에서의 처음 문자여야 합니다. 모든 선택이 circumflex로 시작하는, 목표의 처음에만 매치하는 패턴은 "고정" 패턴이라 불려집니다. (패턴을 고정하는 다른 구조도 존재합니다)

달러 문자는 매칭 위치가 목표 문자열의 마지막이거나, (기본값으로) 문자열 마지막 줄바꿈의 바로 전에 해당하는 경우에만 TRUE인 단정입니다. 선택을 가지는 패턴에서는 달러가 패턴의 마지막일 필요가 없지만, 마지막을 나타내는 모든 브랜치에서 마지막 문자여야 합니다. 달러는 문자 클래스 안에서는 특별한 의미를 가지지 않습니다.

달러의 의미는 컴파일시나 매치를 할 때 PCRE_DOLLAR_ENDONLY 옵션을 설정해서 문자열의 마지막에만 매치하도록 변경할 수 있습니다. 이는 \Z 단정에는 영향을 주지 않습니다.

PCRE_MULTILINE 옵션을 설정하면, circumflex와 달러 문자의 의미가 달라집니다. 이 경우, 목표 문자열의 처음과 마지막에 더하여, 내부의 "\n" 문자의 뒤와 앞에도 매치합니다. 예를 들어, 패턴 /^abc$/는 멀티라인 모드에서는 목표 문자열 "def\nabc"에 매치하지만, 그렇지 않다면 매치하지 않습니다. 따라서, 모든 브랜치가 "^"로 시작하는 브랜치는 단일라인 모드에서는 고정이지만, 멀티라인 모드에서는 고정이 아닙니다. PCRE_MULTILINE을 설정하면, PCRE_DOLLOR_ENDONLY 옵션을 무시합니다.

어떤 모드에서라도 \A, \Z, \z 시퀀스는 목표의 처음과 마지막에 매치할 때 사용할 수 있습니다. PCRE_MULTILINE에 관계 없이 모든 브랜치가 \A로 시작하는 패턴은 항상 고정입니다.

마침표

문자 클래스 밖에서, 패턴의 마침표는 패턴의 아무 문자에 매치합니다. 출력할 수 없는 문자도 포함하지만, (기본값으로) 줄바꿈은 포함하지 않습니다. PCRE_DOTALL 옵션을 설정하면, 마침표가 줄바꿈에도 매치합니다. 마침표의 처리는 circumflex와 달러의 처리와는 완전히 독립이며, 유일한 관계는 두 경우 모두 줄바꿈 문자에 해당한다는 점입니다. 마침표는 문자 클래스 안에서는 특별한 의미를 가지지 않습니다.

대괄호

여는 대괄호로 문자 클래스를 시작하고, 닫는 대괄호로 종료합니다. 닫는 대괄호는 그 자체로는 특별한 의미가 없습니다. 닫는 대괄호를 클래스의 멤버로 사용하려면 클래스의 가장 처음(존재한다면 시작 circumflex 뒤에)에 위치하거나 백슬래쉬로 이스케이프해야 합니다.

문자 클래스는 목표에서 하나의 문자에 매치합니다; 그 문자는 클래스가 정의하는 문자 세트에 존재해야 합니다. 클래스가 circumflex로 시작할 경우에는, 목표 문자는 클래스 정의 세트에 존재하지 않아야 합니다. circumflex가 클래스 멤버로 필요할 때는, 처음에 위치시키지 않거나 백슬래쉬로 이스케이프해야 합니다.

예를 들면, 문자 클래스 [aeiou]는 모든 소문자 모음에 매치하지만, [^aeiow]는 소문자 모음이 아닌 모든 문자에 매치합니다. circumflex는 단지 클래스에 존재하는 문자가 아닌 것들을 지정하는 편리한 방법일 뿐이라는 점에 주의하십시오. 단정이 아닙니다: 목표 문자열에서 문자를 찾아내며, 현재 위치가 문자열의 끝이면 실패합니다.

대소문자를 구별하지 않는 매칭을 설정하면, 클래스 안의 모든 문자는 대문자와 소문자 모두 매치합니다. 예를 들면, 대소문자 구별 없는 [aeiou]는 "a"와 함께 "A"도 매치하며, 대소문자 구별 없는 [^aeiou]는 구별하는 버전일 경우 매치하는 "A"에는 매치하지 않습니다.

줄바꿈 문자는 PCRE_DOTALLPCRE_MULTILINE 옵션의 설정에 관계 없이, 문자 클래스 안에서 특별한 방법으로 취급하지 않습니다. [^a]와 같은 클래스는 항상 줄바꿈에 매치합니다.

빼기(하이픈) 문자는 문자 클래스에서 문자의 범위를 지정하는데 사용할 수 있습니다. 예를 들어, [d-m]은 d부터 m까지의 모든 문자에 매치합니다. 빼기 문자가 클래스에서 필요하면, 백슬래쉬로 이스케이프하거나, 클래스의 맨 처음이나 마지막처럼 범위로 해석할 수 없는 위치에 나타나야 합니다.

문자 "]"를 범위의 마지막으로 지정하는 것은 불가능합니다. [W-]46]과 같은 패턴은 두 문자를 가지는 클래스("W"와 "-") 뒤에 일반 문자열 "46]"이 붙는 형태로 해석합니다. 그러므로 "W46]"이나 "-46]"에 매치합니다. 그러나, "]"를 백슬래쉬로 이스케이프하면 범위의 끝으로 해석하기에, [W-\]46]은 범위와 두개의 개별 문자를 가지는 하나의 클래스로 해석합니다. 범위의 마지막으로 "]"의 8진수 및 16진수 표현을 사용할 수도 있습니다.

범위는 아스키 순서에 따라 정해집니다. [\000-\037]처럼 숫자로 지정한 문자를 사용할 수도 있습니다. 대소문자 구별 없는 매칭을 설정하면, 범위 안의 문자들도 대소문자 구별 없이 매칭합니다. 예를 들면, [W-c]는 대소문자 구별 없는 [][\^_`wxyzabc]와 동일하며, "fr" 로케일의 문자표를 사용하면, [\xc8-\xcb]는 대소문자 구별 없이 엑센트 E 문자에 매치합니다.

문자형 \d, \D, \s, \S, \w, \W도 문자 클래스에서 사용할 수 있고, 해당하는 문자들을 클래스에 추가합니다. 예를 들어, [\dABCDEF]는 모든 16진수에 매치합니다. circumflex와 위에서 대문자형을 지정하여 소문자형을 매칭하는 데에 편리하게 제한을 할 수 있습니다. 예를 들어, 클래스 [^\W_]는 언더스코어를 제외한 모든 문자와 숫자에 매치합니다.

\, -, ^(시작 위치), 종료 ]를 제외한 모든 영숫자가 아닌 문자는 문자 클래스에서 특별한 의미를 가지지 않지만, 이스케이프 해도 문제가 발생하지는 않습니다.

수직 바

수직 바 문자는 선택 패턴을 구별할 때 사용합니다. 예를 들어, 패턴 gilbert|sullivan은 "gilbert"나 "sullivan"에 매치합니다. 어떠한 수의 선택도 사용할 수 있고, 빈 선택도 허용합니다. (빈 문자열에 매칭합니다) 매칭 프로세스는 각 선택을 왼쪽에서 오른쪽으로 시도하며, 가장 먼저 선택한 것을 사용합니다. 서브패턴(아래에서 정의) 안에서 선택을 하면, "성공"은 서브패턴의 선택과 함께 메인 패턴의 나머지 부분도 매치하는 것을 의미합니다.

내부 옵션 설정

PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_EXTENDED의 설정은 "(?"와 ")" 사이에 펄 옵션 문자 시퀀스로 패턴 안에서 변경할 수 있습니다. 옵션 문자는 다음과 같습니다.

내부 옵션 문자
i PCRE_CASELESS에 해당
m PCRE_MULTILINE에 해당
s PCRE_DOTALL에 해당
i PCRE_EXTENDED에 해당

예를 들어, (?im)은 대소문자 구별 없는 멀티라인 매칭을 설정합니다. 하이픈과 함께 사용하여 옵션을 해제할 수도 있습니다. 설정과 해제를 동시에 하는 것도 허용합니다. (?im-sx)를 지정하면, PCRE_CASELESSPCRE_MULTILINE를 설정하고 PCRE_DOTALLPCRE_EXTENDED를 해제합니다. 문자가 하이픈 앞과 뒤에 모두 나타나면, 옵션을 해제합니다.

옵션이 미치는 위치는 패턴의 어디에서 설정을 했는지에 의존합니다. 모든 서브패턴(아래에서 정의) 밖에서 설정하면, 효과는 옵션을 매칭 시작 지점에서 설정 및 해제한 것과 같습니다. 다음 패턴들은 모두 완전히 동일한 작동을 합니다:

      (?i)abc
      a(?i)bc
      ab(?i)c
      abc(?i)
     

이들은 PCRE_CASELESS를 설정하여 패턴 abc를 처리하는 것과 동일합니다. 즉, "최고 레벨" 설정은 (서브패턴 안에서 다른 변화를 주지 않는 한) 모든 패턴에 적용합니다. 최고 레벨에서 같은 옵션의 설정이 하나 이상 존재하면, 가장 오른쪽에 나오는 설정을 사용합니다.

서브패턴 안에서 옵션을 변경하면, 효과가 다릅니다. 이는 펄 5.005에서 작동 변경점입니다. 서브패턴 안에서 옵션 변경은 따라오는 서브패턴의 부분에만 영향을 미칩니다. 그러므로 (a(?i)b)c은 abc와 aBc만을 매치합니다. (PCRE_CASELESS를 사용하지 않는 경우) 이 의미로, 옵션을 패턴의 다른 부분에서 다른 설정으로 할 수 있습니다. 하나의 선택에서 변경한 것은 같은 서브패턴에서 지속적으로 사용합니다. 예를 들면, (a(?i)b|c)는 "ab", "aB", "c", "C"에 매치합니다. "C"는 옵션을 설정하기 전에 나누어진 브랜치에 해당하지만, 이상한 동작일지라도, 처리 시에 옵션 설정의 효율성을 위해서 매치합니다.

PCRE 전용 옵션 PCRE_UNGREEDYPCRE_EXTRA는 U와 X 문자를 사용하여 펄 호환 옵션과 같은 방법으로 변경할 수 있습니다. (?X) 플래그는 특별하기에, 최고 레벨에서라도 다른 기능을 켜기 전에 위치해야만 합니다. 가장 처음에 놓는 편이 좋습니다.

서브패턴

서브패턴은 괄호로 구분하며, 중첩할 수 있습니다. 패턴의 부분을 서브패턴으로 만드는 것은 두가지 일을 합니다:

1. 선택 세트를 지역화합니다. 예를 들어, 패턴 cat(aract|erpillar|)는 "cat", "cataract", "caterpillar" 중에 하나에 매치합니다. 괄호가 없으면, "cataract", "erpillar", 또는 빈 문자열에 매치할 것입니다.

2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

예를 들어, 문자열 "the red king"이 패턴 the ((read|white) (king|queen)에 매치한다면, "red king", "red", "king" 부분 문자열을 잡아내고, 1, 2, 3의 숫자를 부여합니다.

The fact that plain parentheses fulfil two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 99, and the maximum number of all subpatterns, both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

      (?i:saturday|sunday)
      (?:(?i)saturday|sunday)
     

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

반복

반복은 다음 항목들에 덧붙이는 수량어로 지정합니다:

  • 이스케이프할 수 있는 하나의 문자
  • . 메타 문자
  • 문자 클래스
  • 역참조 (다음 섹션 참고)
  • 서브 패턴 묶음(단정이 아닌 경우 - 아래 참고

일반적인 반복 수량어는 허용하는 매치 수의 최소값과 최대값을 중괄호 안에 쉼표로 구분하여 지정합니다. 수는 65535보다 작아야하며, 처음 수는 두번째 수보다 작거나 같아야만 합니다. 예를 들면: z{2,4}는 "zz", "zzz", "zzzz"에 매치합니다. 닫는 괄호 자체는 특수 문자가 아닙니다. 두번째 수를 생략하고, 쉼표가 존재하면 최대 제한이 없어집니다; 두번째 수와 쉼표를 모두 생략하면, 수량어는 요구하는 매치 수의 정확한 수를 지정합니다. 그러므로, [aeiou]{3,}는 3개 이상의 모음에 매치하지만, \d{8}은 8자리 수에만 매치합니다. 수량어를 허용하지 않는 위치에서 중괄호를 여는 것은 수량어 구문으로 매치하지 않고, 일반 문자로 취급합니다. 예를 들어, {,6}는 수량어가 아닌, 4 문자의 일반 문자열입니다.

수량어 {0}을 허용하며, 이는 이전의 항목과 수량어가 존재하지 않는 표현식으로 작동합니다.

편의성을 위해서 (그리고 역사적인 호환성을 위해서) 가장 일반적인 세 수량어는 단일 표현을 가지고 있습니다:

단일 문자 수량어
* {0,}과 동일
+ {1,}과 동일
? {0,1}과 동일

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example: (a?)*

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern /\*.*\*/ to the string /* first command */ not comment /* second comment */ fails, because it matches the entire string due to the greediness of the .* item.

However, if a quantifier is followed by a question mark, then it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern /\*.*?\*/ does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in \d??\d which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum.

If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, then the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE treats such a pattern as though it were preceded by \A. In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after (tweedle[dume]{3}\s*)+ has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after /(a|(b))+/ matches "aba" the value of the second captured substring is "b".

역참조

Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses.

However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. See the section entitled "Backslash" above for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If caseful matching is in force at the time of the back reference, then the case of letters is relevant. For example, ((?i)rah)\s+\1 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched caselessly.

There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, then any back references to it always fail. For example, the pattern (a|(bc))\2 always fails if it starts to match "a" rather than "bc". Because there may be up to 99 back references, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, then some delimiter must be used to terminate the back reference. If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty comment can be used.

A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern (a|b\1)+ matches any number of "a"s and also "aba", "ababaa" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero.

단정

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \Z, \z, ^ and $ are described above. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example, \w+(?=;) matches a word followed by a semicolon, but does not include the semicolon in the match, and foo(?!bar) matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern (?!foo)bar does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always TRUE when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example, (?<!foo)bar does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus (?<=bullock|donkey) is permitted, but (?<!dogs?|cats?) causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl 5.005, which requires all branches to match the same length of string. An assertion such as (?<=ab(c|de)) is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches: (?<=abc|abde) The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns can be particularly useful for matching at the ends of strings; an example is given at the end of the section on once-only subpatterns.

Several assertions (of any sort) may occur in succession. For example, (?<=\d{3})(?<!999)foo matches "foo" preceded by three digits that are not "999". Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, then there is a check that the same three characters are not "999". This pattern does not match "foo" preceded by six characters, the first of which are digits and the last three of which are not "999". For example, it doesn't match "123abcfoo". A pattern to do that is (?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not "999".

Assertions can be nested in any combination. For example, (?<=(?<!foo)bar)baz matches an occurrence of "baz" that is preceded by "bar" which in turn is not preceded by "foo", while (?<=\d{3}(?!999)...)foo is another pattern which matches "foo" preceded by three digits and any three characters that are not "999". Assertion subpatterns are not capturing subpatterns, and may not be repeated, because it makes no sense to assert the same thing several times. If any kind of assertion contains capturing subpatterns within it, these are counted for the purposes of numbering the capturing subpatterns in the whole pattern. However, substring capturing is carried out only for positive assertions, because it does not make sense for negative assertions. Assertions count towards the maximum of 200 parenthesized subpatterns.

Once-only subpatterns

With both maximizing and minimizing repetition, failure of what follows normally causes the repeated item to be reevaluated to see if a different number of repeats allows the rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of the match, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there is no point in carrying on.

Consider, for example, the pattern \d+foo when applied to the subject line 123456bar

After matching all 6 digits and then failing to match "foo", the normal action of the matcher is to try again with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing. Once-only subpatterns provide the means for specifying that once a portion of the pattern has matched, it is not to be re-evaluated in this way, so the matcher would give up immediately on failing to match "foo" the first time. The notation is another kind of special parenthesis, starting with (?> as in this example: (?>\d+)bar

This kind of parenthesis "locks up" the part of the pattern it contains once it has matched, and a failure further into the pattern is prevented from backtracking into it. Backtracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type matches the string of characters that an identical standalone pattern would match, if anchored at the current point in the subject string.

Once-only subpatterns are not capturing subpatterns. Simple cases such as the above example can be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and \d+? are prepared to adjust the number of digits they match in order to make the rest of the pattern match, (?>\d+) can only match an entire sequence of digits.

This construction can of course contain arbitrarily complicated subpatterns, and it can be nested.

Once-only subpatterns can be used in conjunction with lookbehind assertions to specify efficient matching at the end of the subject string. Consider a simple pattern such as abcd$ when applied to a long string which does not match. Because matching proceeds from left to right, PCRE will look for each "a" in the subject and then see if what follows matches the rest of the pattern. If the pattern is specified as ^.*abcd$ then the initial .* matches the entire string at first, but when this fails (because there is no following "a"), it backtracks to match all but the last character, then all but the last two characters, and so on. Once again the search for "a" covers the entire string, from right to left, so we are no better off. However, if the pattern is written as ^(?>.*)(?<=abcd) then there can be no backtracking for the .* item; it can match only the entire string. The subsequent lookbehind assertion does a single test on the last four characters. If it fails, the match fails immediately. For long strings, this approach makes a significant difference to the processing time.

When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of a once-only subpattern is the only way to avoid some failing matches taking a very long time indeed. The pattern (\D+|<\d+>)*[!?] matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa it takes a long time before reporting failure. This is because the string can be divided between the two repeats in a large number of ways, and all have to be tried. (The example used [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) If the pattern is changed to ((?>\D+)|<\d+>)*[!?] sequences of non-digits cannot be broken, and failure happens quickly.

Conditional subpatterns

It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are

      (?(condition)yes-pattern)
      (?(condition)yes-pattern|no-pattern)
     

If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.

There are two kinds of condition. If the text between the parentheses consists of a sequence of digits, then the condition is satisfied if the capturing subpattern of that number has previously matched. Consider the following pattern, which contains non-significant white space to make it more readable (assume the PCRE_EXTENDED option) and to divide it into three parts for ease of discussion: ( \( )? [^()]+ (?(1) \) )

The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is TRUE, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.

If the condition is not a sequence of digits, it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:

      (?(?=[^a-z]*[a-z])
      \d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )
     

The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.

주석

The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all.

If the PCRE_EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.

재귀 패턴

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). The special item (?R) is provided for the specific case of recursion. This PCRE pattern solves the parentheses problem (assume the PCRE_EXTENDED option is set so that white space is ignored): \( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis.

This particular example pattern contains nested unlimited repeats, and so the use of a once-only subpattern for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when it is applied to (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() it yields "no match" quickly. However, if a once-only subpattern is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported.

The values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If the pattern above is matched against (ab(cd)ef) the value for the capturing parentheses is "ef", which is the last value taken on at the top level. If additional parentheses are added, giving \( ( ( (?>[^()]+) | (?R) )* ) \) then the string they capture is "ab(cd)ef", the contents of the top level parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre_malloc, freeing it via pcre_free afterwards. If no memory can be obtained, it saves data for the first 15 capturing parentheses only, as there is no way to give an out-of-memory error from within a recursion.

성능

패턴에 사용하는 몇몇 항목은 다른 항목에 비해서 더욱 효율적입니다. (a|e|i|o|u)처럼 선택을 설정하는 것 보다 [aeiou]처럼 문자 클래스를 사용하는 편이 더욱 효율적입니다. 보통, 요구하는 행동을 제공하는 가장 간단한 구조가 가장 효율적입니다. Jeffrey Friedl의 책은 효율적인 성능을 위한 정규표현식 최적화에 관한 많은 내용을 담고 있습니다.

When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is implicitly anchored by PCRE, since it can match only at the start of a subject string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization, because the . metacharacter does not then match a newline, and if the subject string contains newlines, the pattern may match from the character immediately following one of them instead of from the very start. For example, the pattern (.*) second matches the subject "first\nand second" (where \n stands for a newline character) with the first captured substring being "and". In order to do this, PCRE has to retry the match starting after every newline in the subject.

If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at.

Beware of patterns that contain nested indefinite repeats. These can take a long time to run when applied to a string that does not match. Consider the pattern fragment (a+)*

This can match "aaaa" in 33 different ways, and this number increases very rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4 times, and for each of those cases other than 0, the + repeats can match different numbers of times.) When the remainder of the pattern is such that the entire match is going to fail, PCRE has in principle to try every possible variation, and this can take an extremely long time.

An optimization catches some of the more simple cases such as (a+)*b where a literal character follows. Before embarking on the standard matching procedure, PCRE checks that there is a "b" later in the subject string, and if there is not, it fails the match immediately. However, when there is no following literal this optimization cannot be used. You can see the difference by comparing the behaviour of (a+)*\d with the pattern above. The former gives a failure almost instantly when applied to a whole line of "a" characters, whereas the latter takes an appreciable time with strings longer than about 20 characters.