This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update Unicode-Collate to CPAN version 0.77
[perl5.git] / pod / perlrequick.pod
CommitLineData
47f9c88b
GS
1=head1 NAME
2
3perlrequick - Perl regular expressions quick start
4
5=head1 DESCRIPTION
6
7This page covers the very basics of understanding, creating and
6425a278
GS
8using regular expressions ('regexes') in Perl.
9
47f9c88b
GS
10
11=head1 The Guide
12
13=head2 Simple word matching
14
6425a278
GS
15The simplest regex is simply a word, or more generally, a string of
16characters. A regex consisting of a word matches any string that
47f9c88b
GS
17contains that word:
18
19 "Hello World" =~ /World/; # matches
20
6425a278 21In this statement, C<World> is a regex and the C<//> enclosing
1e2a213d 22C</World/> tells Perl to search a string for a match. The operator
6425a278
GS
23C<=~> associates the string with the regex match and produces a true
24value if the regex matched, or false if the regex did not match. In
47f9c88b
GS
25our case, C<World> matches the second word in C<"Hello World">, so the
26expression is true. This idea has several variations.
27
28Expressions like this are useful in conditionals:
29
30 print "It matches\n" if "Hello World" =~ /World/;
31
32The sense of the match can be reversed by using C<!~> operator:
33
34 print "It doesn't match\n" if "Hello World" !~ /World/;
35
6425a278 36The literal string in the regex can be replaced by a variable:
47f9c88b
GS
37
38 $greeting = "World";
39 print "It matches\n" if "Hello World" =~ /$greeting/;
40
41If you're matching against C<$_>, the C<$_ =~> part can be omitted:
42
43 $_ = "Hello World";
44 print "It matches\n" if /World/;
45
46Finally, the C<//> default delimiters for a match can be changed to
47arbitrary delimiters by putting an C<'m'> out front:
48
49 "Hello World" =~ m!World!; # matches, delimited by '!'
50 "Hello World" =~ m{World}; # matches, note the matching '{}'
51 "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
52 # '/' becomes an ordinary char
53
6425a278 54Regexes must match a part of the string I<exactly> in order for the
47f9c88b
GS
55statement to be true:
56
57 "Hello World" =~ /world/; # doesn't match, case sensitive
58 "Hello World" =~ /o W/; # matches, ' ' is an ordinary char
59 "Hello World" =~ /World /; # doesn't match, no ' ' at end
60
1e2a213d 61Perl will always match at the earliest possible point in the string:
47f9c88b
GS
62
63 "Hello World" =~ /o/; # matches 'o' in 'Hello'
64 "That hat is red" =~ /hat/; # matches 'hat' in 'That'
65
66Not all characters can be used 'as is' in a match. Some characters,
6425a278 67called B<metacharacters>, are reserved for use in regex notation.
47f9c88b
GS
68The metacharacters are
69
70 {}[]()^$.|*+?\
71
72A metacharacter can be matched by putting a backslash before it:
73
74 "2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter
75 "2+2=4" =~ /2\+2/; # matches, \+ is treated like an ordinary +
76 'C:\WIN32' =~ /C:\\WIN/; # matches
5d525260 77 "/usr/bin/perl" =~ /\/usr\/bin\/perl/; # matches
47f9c88b 78
6425a278
GS
79In the last regex, the forward slash C<'/'> is also backslashed,
80because it is used to delimit the regex.
47f9c88b
GS
81
82Non-printable ASCII characters are represented by B<escape sequences>.
83Common examples are C<\t> for a tab, C<\n> for a newline, and C<\r>
84for a carriage return. Arbitrary bytes are represented by octal
85escape sequences, e.g., C<\033>, or hexadecimal escape sequences,
86e.g., C<\x1B>:
87
9f5650a8
KW
88 "1000\t2000" =~ m(0\t2) # matches
89 "cat" =~ /\143\x61\x74/ # matches in ASCII, but a weird way to spell cat
47f9c88b 90
caedc70b 91Regexes are treated mostly as double-quoted strings, so variable
47f9c88b
GS
92substitution works:
93
94 $foo = 'house';
95 'cathouse' =~ /cat$foo/; # matches
96 'housecat' =~ /${foo}cat/; # matches
97
6425a278 98With all of the regexes above, if the regex matched anywhere in the
47f9c88b
GS
99string, it was considered a match. To specify I<where> it should
100match, we would use the B<anchor> metacharacters C<^> and C<$>. The
101anchor C<^> means match at the beginning of the string and the anchor
102C<$> means match at the end of the string, or before a newline at the
103end of the string. Some examples:
104
6425a278
GS
105 "housekeeper" =~ /keeper/; # matches
106 "housekeeper" =~ /^keeper/; # doesn't match
107 "housekeeper" =~ /keeper$/; # matches
108 "housekeeper\n" =~ /keeper$/; # matches
109 "housekeeper" =~ /^housekeeper$/; # matches
47f9c88b
GS
110
111=head2 Using character classes
112
113A B<character class> allows a set of possible characters, rather than
6425a278 114just a single character, to match at a particular point in a regex.
47f9c88b
GS
115Character classes are denoted by brackets C<[...]>, with the set of
116characters to be possibly matched inside. Here are some examples:
117
118 /cat/; # matches 'cat'
6425a278 119 /[bcr]at/; # matches 'bat', 'cat', or 'rat'
47f9c88b
GS
120 "abc" =~ /[cab]/; # matches 'a'
121
122In the last statement, even though C<'c'> is the first character in
6425a278 123the class, the earliest point at which the regex can match is C<'a'>.
47f9c88b
GS
124
125 /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
126 # 'yes', 'Yes', 'YES', etc.
127 /yes/i; # also match 'yes' in a case-insensitive way
128
129The last example shows a match with an C<'i'> B<modifier>, which makes
130the match case-insensitive.
131
132Character classes also have ordinary and special characters, but the
133sets of ordinary and special characters inside a character class are
134different than those outside a character class. The special
135characters for a character class are C<-]\^$> and are matched using an
136escape:
137
138 /[\]c]def/; # matches ']def' or 'cdef'
139 $x = 'bcr';
140 /[$x]at/; # matches 'bat, 'cat', or 'rat'
141 /[\$x]at/; # matches '$at' or 'xat'
142 /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
143
144The special character C<'-'> acts as a range operator within character
145classes, so that the unwieldy C<[0123456789]> and C<[abc...xyz]>
146become the svelte C<[0-9]> and C<[a-z]>:
147
148 /item[0-9]/; # matches 'item0' or ... or 'item9'
149 /[0-9a-fA-F]/; # matches a hexadecimal digit
150
151If C<'-'> is the first or last character in a character class, it is
152treated as an ordinary character.
153
154The special character C<^> in the first position of a character class
155denotes a B<negated character class>, which matches any character but
6425a278 156those in the brackets. Both C<[...]> and C<[^...]> must match a
47f9c88b
GS
157character, or the match fails. Then
158
159 /[^a]at/; # doesn't match 'aat' or 'at', but matches
160 # all other 'bat', 'cat, '0at', '%at', etc.
161 /[^0-9]/; # matches a non-numeric character
162 /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary
163
caedc70b
FC
164Perl has several abbreviations for common character classes. (These
165definitions are those that Perl uses in ASCII mode with the C</a> modifier.
166See L<perlrecharclass/Backslash sequences> for details.)
47f9c88b
GS
167
168=over 4
169
170=item *
551e1d92 171
5d525260
CW
172\d is a digit and represents
173
174 [0-9]
47f9c88b
GS
175
176=item *
551e1d92 177
5d525260
CW
178\s is a whitespace character and represents
179
180 [\ \t\r\n\f]
47f9c88b
GS
181
182=item *
551e1d92 183
5d525260
CW
184\w is a word character (alphanumeric or _) and represents
185
186 [0-9a-zA-Z_]
47f9c88b
GS
187
188=item *
551e1d92 189
5d525260
CW
190\D is a negated \d; it represents any character but a digit
191
192 [^0-9]
47f9c88b
GS
193
194=item *
551e1d92 195
5d525260
CW
196\S is a negated \s; it represents any non-whitespace character
197
198 [^\s]
47f9c88b
GS
199
200=item *
551e1d92 201
5d525260
CW
202\W is a negated \w; it represents any non-word character
203
204 [^\w]
47f9c88b
GS
205
206=item *
551e1d92 207
47f9c88b
GS
208The period '.' matches any character but "\n"
209
210=back
211
212The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
213of character classes. Here are some in use:
214
215 /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
216 /[\d\s]/; # matches any digit or whitespace character
217 /\w\W\w/; # matches a word char, followed by a
218 # non-word char, followed by a word char
219 /..rt/; # matches any two chars, followed by 'rt'
220 /end\./; # matches 'end.'
221 /end[.]/; # same thing, matches 'end.'
222
223The S<B<word anchor> > C<\b> matches a boundary between a word
224character and a non-word character C<\w\W> or C<\W\w>:
225
226 $x = "Housecat catenates house and cat";
227 $x =~ /\bcat/; # matches cat in 'catenates'
228 $x =~ /cat\b/; # matches cat in 'housecat'
229 $x =~ /\bcat\b/; # matches 'cat' at end of string
230
231In the last example, the end of the string is considered a word
232boundary.
233
234=head2 Matching this or that
235
da75cd15 236We can match different character strings with the B<alternation>
6425a278 237metacharacter C<'|'>. To match C<dog> or C<cat>, we form the regex
1e2a213d 238C<dog|cat>. As before, Perl will try to match the regex at the
47f9c88b 239earliest possible point in the string. At each character position,
1e2a213d
KW
240Perl will first try to match the first alternative, C<dog>. If
241C<dog> doesn't match, Perl will then try the next alternative, C<cat>.
242If C<cat> doesn't match either, then the match fails and Perl moves to
47f9c88b
GS
243the next position in the string. Some examples:
244
245 "cats and dogs" =~ /cat|dog|bird/; # matches "cat"
246 "cats and dogs" =~ /dog|cat|bird/; # matches "cat"
247
6425a278 248Even though C<dog> is the first alternative in the second regex,
47f9c88b
GS
249C<cat> is able to match earlier in the string.
250
251 "cats" =~ /c|ca|cat|cats/; # matches "c"
252 "cats" =~ /cats|cat|ca|c/; # matches "cats"
253
254At a given character position, the first alternative that allows the
210b36aa 255regex match to succeed will be the one that matches. Here, all the
5d525260 256alternatives match at the first string position, so the first matches.
47f9c88b
GS
257
258=head2 Grouping things and hierarchical matching
259
6425a278
GS
260The B<grouping> metacharacters C<()> allow a part of a regex to be
261treated as a single unit. Parts of a regex are grouped by enclosing
262them in parentheses. The regex C<house(cat|keeper)> means match
47f9c88b
GS
263C<house> followed by either C<cat> or C<keeper>. Some more examples
264are
265
266 /(a|b)b/; # matches 'ab' or 'bb'
267 /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
268
269 /house(cat|)/; # matches either 'housecat' or 'house'
270 /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
271 # 'house'. Note groups can be nested.
272
273 "20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
274 # because '20\d\d' can't match
275
276=head2 Extracting matches
277
278The grouping metacharacters C<()> also allow the extraction of the
279parts of a string that matched. For each grouping, the part that
280matched inside goes into the special variables C<$1>, C<$2>, etc.
281They can be used just as ordinary variables:
282
283 # extract hours, minutes, seconds
284 $time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
285 $hours = $1;
286 $minutes = $2;
287 $seconds = $3;
288
6425a278 289In list context, a match C</regex/> with groupings will return the
47f9c88b
GS
290list of matched values C<($1,$2,...)>. So we could rewrite it as
291
292 ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
293
6425a278 294If the groupings in a regex are nested, C<$1> gets the group with the
47f9c88b 295leftmost opening parenthesis, C<$2> the next opening parenthesis,
6425a278 296etc. For example, here is a complex regex and the matching variables
47f9c88b
GS
297indicated below it:
298
299 /(ab(cd|ef)((gi)|j))/;
300 1 2 34
301
302Associated with the matching variables C<$1>, C<$2>, ... are
d8b950dc 303the B<backreferences> C<\g1>, C<\g2>, ... Backreferences are
6425a278 304matching variables that can be used I<inside> a regex:
47f9c88b 305
d8b950dc 306 /(\w\w\w)\s\g1/; # find sequences like 'the the' in string
47f9c88b 307
d8b950dc
KW
308C<$1>, C<$2>, ... should only be used outside of a regex, and C<\g1>,
309C<\g2>, ... only inside a regex.
47f9c88b
GS
310
311=head2 Matching repetitions
312
313The B<quantifier> metacharacters C<?>, C<*>, C<+>, and C<{}> allow us
6425a278 314to determine the number of repeats of a portion of a regex we
47f9c88b
GS
315consider to be a match. Quantifiers are put immediately after the
316character, character class, or grouping that we want to specify. They
317have the following meanings:
318
319=over 4
320
cb49b31f
RB
321=item *
322
323C<a?> = match 'a' 1 or 0 times
324
325=item *
326
327C<a*> = match 'a' 0 or more times, i.e., any number of times
328
329=item *
47f9c88b 330
cb49b31f 331C<a+> = match 'a' 1 or more times, i.e., at least once
47f9c88b 332
cb49b31f 333=item *
47f9c88b 334
cb49b31f 335C<a{n,m}> = match at least C<n> times, but not more than C<m>
47f9c88b
GS
336times.
337
cb49b31f
RB
338=item *
339
340C<a{n,}> = match at least C<n> or more times
341
342=item *
47f9c88b 343
cb49b31f 344C<a{n}> = match exactly C<n> times
47f9c88b
GS
345
346=back
347
348Here are some examples:
349
350 /[a-z]+\s+\d*/; # match a lowercase word, at least some space, and
351 # any number of digits
d8b950dc 352 /(\w+)\s+\g1/; # match doubled words of arbitrary length
c2ac8995
NS
353 $year =~ /^\d{2,4}$/; # make sure year is at least 2 but not more
354 # than 4 digits
355 $year =~ /^\d{4}$|^\d{2}$/; # better match; throw out 3 digit dates
47f9c88b
GS
356
357These quantifiers will try to match as much of the string as possible,
6425a278 358while still allowing the regex to match. So we have
47f9c88b 359
6425a278 360 $x = 'the cat in the hat';
47f9c88b
GS
361 $x =~ /^(.*)(at)(.*)$/; # matches,
362 # $1 = 'the cat in the h'
363 # $2 = 'at'
364 # $3 = '' (0 matches)
365
366The first quantifier C<.*> grabs as much of the string as possible
6425a278 367while still having the regex match. The second quantifier C<.*> has
47f9c88b
GS
368no string left to it, so it matches 0 times.
369
370=head2 More matching
371
372There are a few more things you might want to know about matching
72606c45 373operators.
47f9c88b
GS
374The global modifier C<//g> allows the matching operator to match
375within a string as many times as possible. In scalar context,
376successive matches against a string will have C<//g> jump from match
377to match, keeping track of position in the string as it goes along.
378You can get or set the position with the C<pos()> function.
379For example,
380
381 $x = "cat dog house"; # 3 words
382 while ($x =~ /(\w+)/g) {
383 print "Word is $1, ends at position ", pos $x, "\n";
384 }
385
386prints
387
388 Word is cat, ends at position 3
389 Word is dog, ends at position 7
390 Word is house, ends at position 13
391
392A failed match or changing the target string resets the position. If
393you don't want the position reset after failure to match, add the
6425a278 394C<//c>, as in C</regex/gc>.
47f9c88b
GS
395
396In list context, C<//g> returns a list of matched groupings, or if
6425a278 397there are no groupings, a list of matches to the whole regex. So
47f9c88b
GS
398
399 @words = ($x =~ /(\w+)/g); # matches,
400 # $word[0] = 'cat'
401 # $word[1] = 'dog'
402 # $word[2] = 'house'
403
404=head2 Search and replace
405
6425a278 406Search and replace is performed using C<s/regex/replacement/modifiers>.
caedc70b 407The C<replacement> is a Perl double-quoted string that replaces in the
6425a278 408string whatever is matched with the C<regex>. The operator C<=~> is
47f9c88b 409also used here to associate a string with C<s///>. If matching
caedc70b
FC
410against C<$_>, the S<C<$_ =~>> can be dropped. If there is a match,
411C<s///> returns the number of substitutions made; otherwise it returns
47f9c88b
GS
412false. Here are a few examples:
413
414 $x = "Time to feed the cat!";
415 $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
416 $y = "'quoted words'";
417 $y =~ s/^'(.*)'$/$1/; # strip single quotes,
418 # $y contains "quoted words"
419
420With the C<s///> operator, the matched variables C<$1>, C<$2>, etc.
421are immediately available for use in the replacement expression. With
422the global modifier, C<s///g> will search and replace all occurrences
6425a278 423of the regex in the string:
47f9c88b
GS
424
425 $x = "I batted 4 for 4";
426 $x =~ s/4/four/; # $x contains "I batted four for 4"
427 $x = "I batted 4 for 4";
428 $x =~ s/4/four/g; # $x contains "I batted four for four"
429
4f4d7508
DC
430The non-destructive modifier C<s///r> causes the result of the substitution
431to be returned instead of modifying C<$_> (or whatever variable the
432substitute was bound to with C<=~>):
433
434 $x = "I like dogs.";
435 $y = $x =~ s/dogs/cats/r;
436 print "$x $y\n"; # prints "I like dogs. I like cats."
437
438 $x = "Cats are great.";
439 print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~ s/Frogs/Hedgehogs/r, "\n";
440 # prints "Hedgehogs are great."
441
442 @foo = map { s/[a-z]/X/r } qw(a b c 1 2 3);
443 # @foo is now qw(X X X 1 2 3)
444
47f9c88b
GS
445The evaluation modifier C<s///e> wraps an C<eval{...}> around the
446replacement string and the evaluated result is substituted for the
6425a278 447matched substring. Some examples:
47f9c88b 448
6425a278
GS
449 # reverse all the words in a string
450 $x = "the cat in the hat";
451 $x =~ s/(\w+)/reverse $1/ge; # $x contains "eht tac ni eht tah"
47f9c88b 452
6425a278
GS
453 # convert percentage to decimal
454 $x = "A 39% hit rate";
455 $x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"
47f9c88b 456
6425a278
GS
457The last example shows that C<s///> can use other delimiters, such as
458C<s!!!> and C<s{}{}>, and even C<s{}//>. If single quotes are used
caedc70b 459C<s'''>, then the regex and replacement are treated as single-quoted
6425a278 460strings.
47f9c88b
GS
461
462=head2 The split operator
463
6425a278
GS
464C<split /regex/, string> splits C<string> into a list of substrings
465and returns that list. The regex determines the character sequence
47f9c88b
GS
466that C<string> is split with respect to. For example, to split a
467string into words, use
468
469 $x = "Calvin and Hobbes";
6425a278
GS
470 @word = split /\s+/, $x; # $word[0] = 'Calvin'
471 # $word[1] = 'and'
472 # $word[2] = 'Hobbes'
473
474To extract a comma-delimited list of numbers, use
47f9c88b 475
6425a278
GS
476 $x = "1.618,2.718, 3.142";
477 @const = split /,\s*/, $x; # $const[0] = '1.618'
478 # $const[1] = '2.718'
479 # $const[2] = '3.142'
480
481If the empty regex C<//> is used, the string is split into individual
5d525260 482characters. If the regex has groupings, then the list produced contains
47f9c88b
GS
483the matched substrings from the groupings as well:
484
485 $x = "/usr/bin";
486 @parts = split m!(/)!, $x; # $parts[0] = ''
487 # $parts[1] = '/'
488 # $parts[2] = 'usr'
489 # $parts[3] = '/'
490 # $parts[4] = 'bin'
491
6425a278 492Since the first character of $x matched the regex, C<split> prepended
47f9c88b
GS
493an empty initial element to the list.
494
495=head1 BUGS
496
497None.
498
499=head1 SEE ALSO
500
501This is just a quick start guide. For a more in-depth tutorial on
6425a278 502regexes, see L<perlretut> and for the reference page, see L<perlre>.
47f9c88b
GS
503
504=head1 AUTHOR AND COPYRIGHT
505
506Copyright (c) 2000 Mark Kvale
507All rights reserved.
508
509This document may be distributed under the same terms as Perl itself.
510
6425a278
GS
511=head2 Acknowledgments
512
513The author would like to thank Mark-Jason Dominus, Tom Christiansen,
514Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful
515comments.
516
47f9c88b
GS
517=cut
518