Commit | Line | Data |
---|---|---|
a0d0e21e LW |
1 | =head1 NAME |
2 | ||
3 | perlre - Perl regular expressions | |
4 | ||
5 | =head1 DESCRIPTION | |
6 | ||
7 | For a description of how to use regular expressions in matching | |
8 | operations, see C<m//> and C<s///> in L<perlop>. The matching operations can | |
9 | have various modifiers, some of which relate to the interpretation of | |
10 | the regular expression inside. These are: | |
11 | ||
12 | i Do case-insensitive pattern matching. | |
13 | m Treat string as multiple lines. | |
14 | s Treat string as single line. | |
15 | x Use extended regular expressions. | |
16 | ||
17 | These are usually written as "the C</x> modifier", even though the delimiter | |
18 | in question might not actually be a slash. In fact, any of these | |
19 | modifiers may also be embedded within the regular expression itself using | |
20 | the new C<(?...)> construct. See below. | |
21 | ||
4633a7c4 LW |
22 | The C</x> modifier itself needs a little more explanation. It tells |
23 | the regular expression parser to ignore whitespace that is not | |
24 | backslashed or within a character class. You can use this to break up | |
25 | your regular expression into (slightly) more readable parts. The C<#> | |
26 | character is also treated as a metacharacter introducing a comment, | |
27 | just as in ordinary Perl code. Taken together, these features go a | |
28 | long way towards making Perl 5 a readable language. See the C comment | |
a0d0e21e LW |
29 | deletion code in L<perlop>. |
30 | ||
31 | =head2 Regular Expressions | |
32 | ||
33 | The patterns used in pattern matching are regular expressions such as | |
34 | those supplied in the Version 8 regexp routines. (In fact, the | |
35 | routines are derived (distantly) from Henry Spencer's freely | |
36 | redistributable reimplementation of the V8 routines.) | |
37 | See L<Version 8 Regular Expressions> for details. | |
38 | ||
39 | In particular the following metacharacters have their standard I<egrep>-ish | |
40 | meanings: | |
41 | ||
42 | \ Quote the next metacharacter | |
43 | ^ Match the beginning of the line | |
44 | . Match any character (except newline) | |
45 | $ Match the end of the line | |
46 | | Alternation | |
47 | () Grouping | |
48 | [] Character class | |
49 | ||
50 | By default, the "^" character is guaranteed to match only at the | |
51 | beginning of the string, the "$" character only at the end (or before the | |
52 | newline at the end) and Perl does certain optimizations with the | |
53 | assumption that the string contains only one line. Embedded newlines | |
54 | will not be matched by "^" or "$". You may, however, wish to treat a | |
55 | string as a multi-line buffer, such that the "^" will match after any | |
56 | newline within the string, and "$" will match before any newline. At the | |
57 | cost of a little more overhead, you can do this by using the /m modifier | |
58 | on the pattern match operator. (Older programs did this by setting C<$*>, | |
59 | but this practice is deprecated in Perl 5.) | |
60 | ||
61 | To facilitate multi-line substitutions, the "." character never matches a | |
62 | newline unless you use the C</s> modifier, which tells Perl to pretend | |
63 | the string is a single line--even if it isn't. The C</s> modifier also | |
64 | overrides the setting of C<$*>, in case you have some (badly behaved) older | |
65 | code that sets it in another module. | |
66 | ||
67 | The following standard quantifiers are recognized: | |
68 | ||
69 | * Match 0 or more times | |
70 | + Match 1 or more times | |
71 | ? Match 1 or 0 times | |
72 | {n} Match exactly n times | |
73 | {n,} Match at least n times | |
74 | {n,m} Match at least n but not more than m times | |
75 | ||
76 | (If a curly bracket occurs in any other context, it is treated | |
77 | as a regular character.) The "*" modifier is equivalent to C<{0,}>, the "+" | |
25f94b33 AD |
78 | modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited |
79 | to integral values less than 65536. | |
a0d0e21e LW |
80 | |
81 | By default, a quantified subpattern is "greedy", that is, it will match as | |
82 | many times as possible without causing the rest pattern not to match. The | |
83 | standard quantifiers are all "greedy", in that they match as many | |
84 | occurrences as possible (given a particular starting location) without | |
85 | causing the pattern to fail. If you want it to match the minimum number | |
86 | of times possible, follow the quantifier with a "?" after any of them. | |
87 | Note that the meanings don't change, just the "gravity": | |
88 | ||
89 | *? Match 0 or more times | |
90 | +? Match 1 or more times | |
91 | ?? Match 0 or 1 time | |
92 | {n}? Match exactly n times | |
93 | {n,}? Match at least n times | |
94 | {n,m}? Match at least n but not more than m times | |
95 | ||
96 | Since patterns are processed as double quoted strings, the following | |
97 | also work: | |
98 | ||
99 | \t tab | |
100 | \n newline | |
101 | \r return | |
102 | \f form feed | |
103 | \v vertical tab, whatever that is | |
104 | \a alarm (bell) | |
105 | \e escape | |
106 | \033 octal char | |
107 | \x1b hex char | |
108 | \c[ control char | |
109 | \l lowercase next char | |
110 | \u uppercase next char | |
111 | \L lowercase till \E | |
112 | \U uppercase till \E | |
113 | \E end case modification | |
114 | \Q quote regexp metacharacters till \E | |
115 | ||
116 | In addition, Perl defines the following: | |
117 | ||
118 | \w Match a "word" character (alphanumeric plus "_") | |
119 | \W Match a non-word character | |
120 | \s Match a whitespace character | |
121 | \S Match a non-whitespace character | |
122 | \d Match a digit character | |
123 | \D Match a non-digit character | |
124 | ||
125 | Note that C<\w> matches a single alphanumeric character, not a whole | |
126 | word. To match a word you'd need to say C<\w+>. You may use C<\w>, C<\W>, C<\s>, | |
127 | C<\S>, C<\d> and C<\D> within character classes (though not as either end of a | |
128 | range). | |
129 | ||
130 | Perl defines the following zero-width assertions: | |
131 | ||
132 | \b Match a word boundary | |
133 | \B Match a non-(word boundary) | |
134 | \A Match only at beginning of string | |
135 | \Z Match only at end of string | |
136 | \G Match only where previous m//g left off | |
137 | ||
138 | A word boundary (C<\b>) is defined as a spot between two characters that | |
139 | has a C<\w> on one side of it and and a C<\W> on the other side of it (in | |
140 | either order), counting the imaginary characters off the beginning and | |
141 | end of the string as matching a C<\W>. (Within character classes C<\b> | |
142 | represents backspace rather than a word boundary.) The C<\A> and C<\Z> are | |
143 | just like "^" and "$" except that they won't match multiple times when the | |
144 | C</m> modifier is used, while "^" and "$" will match at every internal line | |
145 | boundary. | |
146 | ||
147 | When the bracketing construct C<( ... )> is used, \<digit> matches the | |
148 | digit'th substring. (Outside of the pattern, always use "$" instead of | |
149 | "\" in front of the digit. The scope of $<digit> (and C<$`>, C<$&>, and C<$')> | |
150 | extends to the end of the enclosing BLOCK or eval string, or to the | |
4633a7c4 | 151 | next successful pattern match, whichever comes first. |
a0d0e21e LW |
152 | If you want to |
153 | use parentheses to delimit subpattern (e.g. a set of alternatives) without | |
154 | saving it as a subpattern, follow the ( with a ?. | |
155 | The \<digit> notation | |
156 | sometimes works outside the current pattern, but should not be relied | |
157 | upon.) You may have as many parentheses as you wish. If you have more | |
158 | than 9 substrings, the variables $10, $11, ... refer to the | |
159 | corresponding substring. Within the pattern, \10, \11, etc. refer back | |
160 | to substrings if there have been at least that many left parens before | |
161 | the backreference. Otherwise (for backward compatibilty) \10 is the | |
162 | same as \010, a backspace, and \11 the same as \011, a tab. And so | |
163 | on. (\1 through \9 are always backreferences.) | |
164 | ||
165 | C<$+> returns whatever the last bracket match matched. C<$&> returns the | |
166 | entire matched string. ($0 used to return the same thing, but not any | |
167 | more.) C<$`> returns everything before the matched string. C<$'> returns | |
168 | everything after the matched string. Examples: | |
169 | ||
170 | s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words | |
171 | ||
172 | if (/Time: (..):(..):(..)/) { | |
173 | $hours = $1; | |
174 | $minutes = $2; | |
175 | $seconds = $3; | |
176 | } | |
177 | ||
178 | You will note that all backslashed metacharacters in Perl are | |
179 | alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular expression | |
180 | languages, there are no backslashed symbols that aren't alphanumeric. | |
181 | So anything that looks like \\, \(, \), \<, \>, \{, or \} is always | |
182 | interpreted as a literal character, not a metacharacter. This makes it | |
183 | simple to quote a string that you want to use for a pattern but that | |
184 | you are afraid might contain metacharacters. Simply quote all the | |
185 | non-alphanumeric characters: | |
186 | ||
187 | $pattern =~ s/(\W)/\\$1/g; | |
188 | ||
189 | You can also use the built-in quotemeta() function to do this. | |
190 | An even easier way to quote metacharacters right in the match operator | |
191 | is to say | |
192 | ||
193 | /$unquoted\Q$quoted\E$unquoted/ | |
194 | ||
195 | Perl 5 defines a consistent extension syntax for regular expressions. | |
196 | The syntax is a pair of parens with a question mark as the first thing | |
197 | within the parens (this was a syntax error in Perl 4). The character | |
198 | after the question mark gives the function of the extension. Several | |
199 | extensions are already supported: | |
200 | ||
201 | =over 10 | |
202 | ||
203 | =item (?#text) | |
204 | ||
205 | A comment. The text is ignored. | |
206 | ||
207 | =item (?:regexp) | |
208 | ||
209 | This groups things like "()" but doesn't make backrefences like "()" does. So | |
210 | ||
211 | split(/\b(?:a|b|c)\b/) | |
212 | ||
213 | is like | |
214 | ||
215 | split(/\b(a|b|c)\b/) | |
216 | ||
217 | but doesn't spit out extra fields. | |
218 | ||
219 | =item (?=regexp) | |
220 | ||
221 | A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/> | |
222 | matches a word followed by a tab, without including the tab in C<$&>. | |
223 | ||
224 | =item (?!regexp) | |
225 | ||
226 | A zero-width negative lookahead assertion. For example C</foo(?!bar)/> | |
227 | matches any occurrence of "foo" that isn't followed by "bar". Note | |
228 | however that lookahead and lookbehind are NOT the same thing. You cannot | |
229 | use this for lookbehind: C</(?!foo)bar/> will not find an occurrence of | |
230 | "bar" that is preceded by something which is not "foo". That's because | |
231 | the C<(?!foo)> is just saying that the next thing cannot be "foo"--and | |
232 | it's not, it's a "bar", so "foobar" will match. You would have to do | |
233 | something like C</(?foo)...bar/> for that. We say "like" because there's | |
234 | the case of your "bar" not having three characters before it. You could | |
235 | cover that this way: C</(?:(?!foo)...|^..?)bar/>. Sometimes it's still | |
236 | easier just to say: | |
237 | ||
238 | if (/foo/ && $` =~ /bar$/) | |
239 | ||
240 | ||
241 | =item (?imsx) | |
242 | ||
243 | One or more embedded pattern-match modifiers. This is particularly | |
244 | useful for patterns that are specified in a table somewhere, some of | |
245 | which want to be case sensitive, and some of which don't. The case | |
246 | insensitive ones merely need to include C<(?i)> at the front of the | |
247 | pattern. For example: | |
248 | ||
249 | $pattern = "foobar"; | |
250 | if ( /$pattern/i ) | |
251 | ||
252 | # more flexible: | |
253 | ||
254 | $pattern = "(?i)foobar"; | |
255 | if ( /$pattern/ ) | |
256 | ||
257 | =back | |
258 | ||
259 | The specific choice of question mark for this and the new minimal | |
260 | matching construct was because 1) question mark is pretty rare in older | |
261 | regular expressions, and 2) whenever you see one, you should stop | |
262 | and "question" exactly what is going on. That's psychology... | |
263 | ||
264 | =head2 Version 8 Regular Expressions | |
265 | ||
266 | In case you're not familiar with the "regular" Version 8 regexp | |
267 | routines, here are the pattern-matching rules not described above. | |
268 | ||
269 | Any single character matches itself, unless it is a I<metacharacter> | |
270 | with a special meaning described here or above. You can cause | |
271 | characters which normally function as metacharacters to be interpreted | |
272 | literally by prefixing them with a "\" (e.g. "\." matches a ".", not any | |
273 | character; "\\" matches a "\"). A series of characters matches that | |
274 | series of characters in the target string, so the pattern C<blurfl> | |
275 | would match "blurfl" in the target string. | |
276 | ||
277 | You can specify a character class, by enclosing a list of characters | |
278 | in C<[]>, which will match any one of the characters in the list. If the | |
279 | first character after the "[" is "^", the class matches any character not | |
280 | in the list. Within a list, the "-" character is used to specify a | |
281 | range, so that C<a-z> represents all the characters between "a" and "z", | |
282 | inclusive. | |
283 | ||
284 | Characters may be specified using a metacharacter syntax much like that | |
285 | used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return, | |
286 | "\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string | |
287 | of octal digits, matches the character whose ASCII value is I<nnn>. | |
288 | Similarly, \xI<nn>, where I<nn> are hexidecimal digits, matches the | |
289 | character whose ASCII value is I<nn>. The expression \cI<x> matches the | |
290 | ASCII character control-I<x>. Finally, the "." metacharacter matches any | |
291 | character except "\n" (unless you use C</s>). | |
292 | ||
293 | You can specify a series of alternatives for a pattern using "|" to | |
294 | separate them, so that C<fee|fie|foe> will match any of "fee", "fie", | |
295 | or "foe" in the target string (as would C<f(e|i|o)e>). Note that the | |
296 | first alternative includes everything from the last pattern delimiter | |
297 | ("(", "[", or the beginning of the pattern) up to the first "|", and | |
298 | the last alternative contains everything from the last "|" to the next | |
299 | pattern delimiter. For this reason, it's common practice to include | |
300 | alternatives in parentheses, to minimize confusion about where they | |
748a9306 LW |
301 | start and end. Note however that "|" is interpreted as a literal with |
302 | square brackets, so if you write C<[fee|fie|foe]> you're really only | |
303 | matching C<[feio|]>. | |
a0d0e21e LW |
304 | |
305 | Within a pattern, you may designate subpatterns for later reference by | |
306 | enclosing them in parentheses, and you may refer back to the I<n>th | |
307 | subpattern later in the pattern using the metacharacter \I<n>. | |
308 | Subpatterns are numbered based on the left to right order of their | |
309 | opening parenthesis. Note that a backreference matches whatever | |
310 | actually matched the subpattern in the string being examined, not the | |
748a9306 | 311 | rules for that subpattern. Therefore, C<(0|0x)\d*\s\1\d*> will |
a0d0e21e | 312 | match "0x1234 0x4321",but not "0x1234 01234", since subpattern 1 |
748a9306 | 313 | actually matched "0x", even though the rule C<0|0x> could |
a0d0e21e | 314 | potentially match the leading 0 in the second number. |