Perl 정규표현식 레퍼런스
Perl 정규표현식 레퍼런스 (perlreref)
Perl 정규표현식의 빠른 참조(quick reference) 문서예요. 전체 정보를 원하면 perlre와 perlop, 그리고 이 문서의 SEE ALSO 섹션을 보세요.
본문
연산자 (OPERATORS)
=~는 정규식을 적용할 변수를 정해요. 생략하면 $_를 사용해요.
$var =~ /foo/;
!~도 정규식을 적용할 변수를 정하지만, 매치 결과를 부정해요. 매치가 성공하면 false를, 실패하면 true를 돌려줘요.
$var !~ /foo/;
m/pattern/msixpogcdualn은 문자열에서 패턴 매치를 검색하고, 주어진 옵션을 적용해요.
m Multiline mode - ^ and $ match internal lines
s match as a Single line - . matches \n
i case-Insensitive
x eXtended legibility - free whitespace and comments
p Preserve a copy of the matched string -
${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
o compile pattern Once
g Global - all occurrences
c don't reset pos on failed matches when using /g
a restrict \d, \s, \w and [:posix:] to match ASCII only
aa (two a's) also /i matches exclude ASCII/non-ASCII
l match according to current locale
u match according to Unicode rules
d match according to native rules unless something indicates
Unicode
n Non-capture mode. Don't let () fill in $1, $2, etc...
'pattern'이 빈 문자열이면, 마지막으로 성공적으로 매치된 정규식이 사용돼요. 이 연산자와 아래 연산자들 모두 '/' 외의 구분자를 쓸 수 있어요. 구분자가 '/'라면 앞의 m은 생략할 수 있어요.
qr/pattern/msixpodualn은 정규식을 변수에 저장하거나 주변에 전달할 수 있게 해 줘요. 수정자는 m//와 같고, 정규식 안에 함께 저장돼요.
s/pattern/replacement/msixpogcedual은 'pattern'의 매치를 'replacement'로 치환해요. 수정자는 m//와 같고 두 가지가 추가돼요:
e Evaluate 'replacement' as an expression
r Return substitution and leave the original string untouched.
'e'는 여러 번 지정할 수 있어요. 'replacement'는 구분자가 작은따옴표(')가 아니면 이중 인용 문자열로 해석돼요.
m?pattern?는 m/pattern/과 같지만 한 번만 매치해요. 다른 구분자는 쓸 수 없어요. reset()으로 재설정해야 해요.
문법 (SYNTAX)
\ Escapes the character immediately following it
. Matches any single character except a newline (unless /s is
used)
^ Matches at the beginning of the string (or line, if /m is used)
$ Matches at the end of the string (or line, if /m is used)
* Matches the preceding element 0 or more times
+ Matches the preceding element 1 or more times
? Matches the preceding element 0 or 1 times
{...} Specifies a range of occurrences for the element preceding it
[...] Matches any one of the characters contained within the brackets
(...) Groups subexpressions for capturing to $1, $2...
(?:...) Groups subexpressions without capturing (cluster)
| Matches either the subexpression preceding or following it
\g1 or \g{1}, \g2 ... Matches the text from the Nth group
\1, \2, \3 ... Matches the text from the Nth group
\g-1 or \g{-1}, \g-2 ... Matches the text from the Nth previous group
\g{name} Named backreference
\k<name> Named backreference
\k'name' Named backreference
(?P=name) Named backreference (python syntax)
이스케이프 시퀀스 (ESCAPE SEQUENCES)
다음은 보통 문자열과 같이 동작해요.
\a Alert (beep)
\e Escape
\f Formfeed
\n Newline
\r Carriage return
\t Tab
\037 Char whose ordinal is the 3 octal digits, max \777
\o{2307} Char whose ordinal is the octal number, unrestricted
\x7f Char whose ordinal is the 2 hex digits, max \xFF
\x{263a} Char whose ordinal is the hex number, unrestricted
\cx Control-x
\N{name} A named Unicode character or character sequence
\N{U+263D} A Unicode character by hex ordinal
\l Lowercase next character
\u Titlecase next character
\L Lowercase until \E
\U Uppercase until \E
\F Foldcase until \E
\Q Disable pattern metacharacters until \E
\E End modification
Titlecase에 대해서는 아래 "Titlecase"를 보세요.
이건 보통 문자열과 다르게 동작해요:
\b An assertion, not backspace, except in a character class
문자 클래스 (CHARACTER CLASSES)
[amy] Match 'a', 'm' or 'y'
[f-j] Dash specifies "range"
[f-j-] Dash escaped or at start or end means 'dash'
[^f-j] Caret indicates "match any character _except_ these"
다음 시퀀스(\N 제외)는 문자 클래스 안팎 모두에서 동작해요. 처음 여섯 개는 locale을 인식하고, 전부 Unicode를 인식해요. 세부 사항은 perllocale과 perlunicode를 보세요.
\d A digit
\D A nondigit
\w A word character
\W A non-word character
\s A whitespace character
\S A non-whitespace character
\h A horizontal whitespace
\H A non horizontal whitespace
\N A non newline (when not followed by '{NAME}';
not valid in a character class; equivalent to [^\n]; it's
like '.' without /s modifier)
\v A vertical whitespace
\V A non vertical whitespace
\R A generic newline (?>\x0D\x0A|\v)
\pP Match P-named (Unicode) property
\p{...} Match Unicode property with name longer than 1 character
\PP Match non-P
\P{...} Match lack of Unicode property with name longer than 1 char
\X Match Unicode extended grapheme cluster
POSIX 문자 클래스와 그 Unicode·Perl 동등 표현:
ASCII- Full-
POSIX range range backslash
[[:...:]] \p{...} \p{...} sequence Description
-----------------------------------------------------------------------
alnum PosixAlnum XPosixAlnum 'alpha' plus 'digit'
alpha PosixAlpha XPosixAlpha Alphabetic characters
ascii ASCII Any ASCII character
blank PosixBlank XPosixBlank \h Horizontal whitespace;
full-range also
written as
\p{HorizSpace}
cntrl PosixCntrl XPosixCntrl Control characters
digit PosixDigit XPosixDigit \d Decimal digits
graph PosixGraph XPosixGraph 'alnum' plus 'punct'
lower PosixLower XPosixLower Lowercase characters
print PosixPrint XPosixPrint 'graph' plus 'space',
but not any Controls
punct PosixPunct XPosixPunct Punctuation and Symbols
in ASCII-range; just
punct outside it
space PosixSpace XPosixSpace \s Whitespace
upper PosixUpper XPosixUpper Uppercase characters
word PosixWord XPosixWord \w 'alnum' + Unicode marks
+ connectors, like
'_' (Perl extension)
xdigit ASCII_Hex_Digit XPosixDigit Hexadecimal digit,
ASCII-range is
[0-9A-Fa-f]
또한 여러 동의어가 있어요. 예를 들어 \p{XPosixAlpha}에 대한 \p{Alpha} 같은 것들이죠. 전부 "Properties accessible through \p{} and \P{}" in perluniprops 문서에 나열돼 있어요.
문자 클래스 안에서:
POSIX traditional Unicode
[:digit:] \d \p{Digit}
[:^digit:] \D \P{Digit}
앵커 (ANCHORS)
모두 너비가 0인 어서션(assertion)이에요.
^ Match string start (or line, if /m is used)
$ Match string end (or line, if /m is used) or before newline
\b{} Match boundary of type specified within the braces
\B{} Match wherever \b{} doesn't match
\b Match word boundary (between \w and \W)
\B Match except at word boundary (between \w and \w or \W and \W)
\A Match string start (regardless of /m)
\Z Match string end (before optional newline)
\z Match absolute string end
\G Match where previous m//g left off
\K Keep the stuff left of the \K, don't include it in $&
수량자 (QUANTIFIERS)
수량자는 기본적으로 탐욕적(greedy)이고 가장 긴 왼쪽 매치를 해요.
Maximal Minimal Possessive Allowed range
------- ------- ---------- -------------
{n,m} {n,m}? {n,m}+ Must occur at least n times
but no more than m times
{n,} {n,}? {n,}+ Must occur at least n times
{,n} {,n}? {,n}+ Must occur at most n times
{n} {n}? {n}+ Must occur exactly n times
* *? *+ 0 or more times (same as {0,})
+ +? ++ 1 or more times (same as {1,})
? ?? ?+ 0 or 1 time (same as {0,1})
소유형(possessive) 형태(Perl 5.10부터)는 역추적(backtracking)을 막아요. 소유형 수량자가 붙은 패턴이 매치한 내용은, 전체 매치가 실패하게 되더라도 역추적되지 않아요.
확장 구조 (EXTENDED CONSTRUCTS)
(?#text) A comment
(?:...) Groups subexpressions without capturing (cluster)
(?pimsx-imsx:...) Enable/disable option (as per m// modifiers)
(?=...) Zero-width positive lookahead assertion
(*pla:...) Same, starting in 5.32; experimentally in 5.28
(*positive_lookahead:...) Same, same versions as *pla
(?!...) Zero-width negative lookahead assertion
(*nla:...) Same, starting in 5.32; experimentally in 5.28
(*negative_lookahead:...) Same, same versions as *nla
(?<=...) Zero-width positive lookbehind assertion
(*plb:...) Same, starting in 5.32; experimentally in 5.28
(*positive_lookbehind:...) Same, same versions as *plb
(?<!...) Zero-width negative lookbehind assertion
(*nlb:...) Same, starting in 5.32; experimentally in 5.28
(*negative_lookbehind:...) Same, same versions as *plb
(?>...) Grab what we can, prohibit backtracking
(*atomic:...) Same, starting in 5.32; experimentally in 5.28
(?|...) Branch reset
(?<name>...) Named capture
(?'name'...) Named capture
(?P<name>...) Named capture (python syntax)
(?[...]) Extended bracketed character class
(?{ code }) Embedded code, return value becomes $^R
(??{ code }) Dynamic regex, return value used as regex
(?N) Recurse into subpattern number N
(?-N), (?+N) Recurse into Nth previous/next subpattern
(?R), (?0) Recurse at the beginning of the whole pattern
(?&name) Recurse into a named subpattern
(?P>name) Recurse into a named subpattern (python syntax)
(?(cond)yes|no)
(?(cond)yes) Conditional expression, where "(cond)" can be:
(?=pat) lookahead; also (*pla:pat)
(*positive_lookahead:pat)
(?!pat) negative lookahead; also (*nla:pat)
(*negative_lookahead:pat)
(?<=pat) lookbehind; also (*plb:pat)
(*lookbehind:pat)
(?<!pat) negative lookbehind; also (*nlb:pat)
(*negative_lookbehind:pat)
(N) subpattern N has matched something
(<name>) named subpattern has matched something
('name') named subpattern has matched something
(?{code}) code condition
(R) true if recursing
(RN) true if recursing into Nth subpattern
(R&name) true if recursing into named subpattern
(DEFINE) always false, no no-pattern allowed
변수 (VARIABLES)
$_ Default variable for operators to use
$` Everything prior to matched string
$& Entire matched string
$' Everything after to matched string
${^PREMATCH} Everything prior to matched string
${^MATCH} Entire matched string
${^POSTMATCH} Everything after to matched string
아직 Perl 5.18 이하를 쓰는 분들을 위한 참고: $``, $&또는$'를 쓰면 프로그램 안의 **모든** 정규식 사용이 느려져요. 속도 저하를 일으키지 않는 동등 표현은 [perlvar](https://perldoc.perl.org/perlvar)의 @-부분을 보세요. [Devel::SawAmpersand](https://metacpan.org/pod/Devel::SawAmpersand)도 참고하세요. Perl 5.10부터는 동등한 변수${^PREMATCH}, ${^MATCH}, ${^POSTMATCH}를 쓸 수도 있는데, 이들이 정의되려면 정규식에 /p(preserve) 수정자를 지정해야 해요. Perl 5.20에서는 $``, $&, $'를 써도 속도 차이가 없어요.
$1, $2 ... hold the Xth captured expr
$+ Last parenthesized pattern match
$^N Holds the most recently closed capture
$^R Holds the result of the last (?{...}) expr
@- Offsets of starts of groups. $-[0] holds start of whole match
@+ Offsets of ends of groups. $+[0] holds end of whole match
%+ Named capture groups
%- Named capture groups, as array refs
캡처 그룹은 그 여는 괄호 기준으로 번호가 매겨져요.
함수 (FUNCTIONS)
lc Lowercase a string
lcfirst Lowercase first char of a string
uc Uppercase a string
ucfirst Titlecase first char of a string
fc Foldcase a string
pos Return or set current match position
quotemeta Quote metacharacters (escape their normal meaning)
reset Reset m?pattern? status
study Analyze string for optimizing matching
split Use a regex to split a string into parts
첫 다섯 개는 이스케이프 시퀀스 \L, \l, \U, \u, \F와 같아요. Titlecase는 "Titlecase"를, Foldcase는 "Foldcase"를 보세요.
용어 (TERMINOLOGY)
Titlecase
Unicode 개념으로, 대부분의 경우 대문자와 같아요. 다만 독일어 "sharp s" 같은 특정 문자에서는 차이가 있어요.
Foldcase
문자열을 대소문자와 무관하게 비교할 때 유용한 Unicode 형태예요. 어떤 문자는 복잡한 일대다(one-to-many) case 매핑을 갖고 있기 때문이에요. 주로 소문자의 변형이에요.
더 알아보기 (SEE ALSO)
- 정규표현식 튜토리얼은 perlretut
- 빠른 튜토리얼은 perlrequick
- 더 자세한 내용은 perlre
- 변수에 대한 내용은 perlvar
- 연산자에 대한 내용은 perlop
- 함수에 대한 내용은 perlfunc
- 정규표현식 FAQ는 perlfaq6
- 백슬래시 시퀀스 참조는 perlrebackslash
- 문자 클래스 참조는 perlrecharclass
- 동작 변경·디버깅에 도움을 주는 re 모듈
- "Debugging Regular Expressions" in perldebug
- 정규식과 국제화에 대한 내용은 perluniintro, perlunicode, charnames, perllocale
- 주제에 대한 철저한 입문과 참조는 Jeffrey Friedl의 Mastering Regular Expressions (https://www.oreilly.com/library/view/-/0596528124/)