1perlfaq6(3) User Contributed Perl Documentation perlfaq6(3)
2
3
4
6 perlfaq6 - Regular Expressions
7
9 version 5.20210520
10
12 This section is surprisingly small because the rest of the FAQ is
13 littered with answers involving regular expressions. For example,
14 decoding a URL and checking whether something is a number can be
15 handled with regular expressions, but those answers are found elsewhere
16 in this document (in perlfaq9: "How do I decode or create those
17 %-encodings on the web" and perlfaq4: "How do I determine whether a
18 scalar is a number/whole/integer/float", to be precise).
19
20 How can I hope to use regular expressions without creating illegible and
21 unmaintainable code?
22 Three techniques can make regular expressions maintainable and
23 understandable.
24
25 Comments Outside the Regex
26 Describe what you're doing and how you're doing it, using normal
27 Perl comments.
28
29 # turn the line into the first word, a colon, and the
30 # number of characters on the rest of the line
31 s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
32
33 Comments Inside the Regex
34 The "/x" modifier causes whitespace to be ignored in a regex
35 pattern (except in a character class and a few other places), and
36 also allows you to use normal comments there, too. As you can
37 imagine, whitespace and comments help a lot.
38
39 "/x" lets you turn this:
40
41 s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
42
43 into this:
44
45 s{ < # opening angle bracket
46 (?: # Non-backreffing grouping paren
47 [^>'"] * # 0 or more things that are neither > nor ' nor "
48 | # or else
49 ".*?" # a section between double quotes (stingy match)
50 | # or else
51 '.*?' # a section between single quotes (stingy match)
52 ) + # all occurring one or more times
53 > # closing angle bracket
54 }{}gsx; # replace with nothing, i.e. delete
55
56 It's still not quite so clear as prose, but it is very useful for
57 describing the meaning of each part of the pattern.
58
59 Different Delimiters
60 While we normally think of patterns as being delimited with "/"
61 characters, they can be delimited by almost any character. perlre
62 describes this. For example, the "s///" above uses braces as
63 delimiters. Selecting another delimiter can avoid quoting the
64 delimiter within the pattern:
65
66 s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
67 s#/usr/local#/usr/share#g; # better
68
69 Using logically paired delimiters can be even more readable:
70
71 s{/usr/local/}{/usr/share}g; # better still
72
73 I'm having trouble matching over more than one line. What's wrong?
74 Either you don't have more than one line in the string you're looking
75 at (probably), or else you aren't using the correct modifier(s) on your
76 pattern (possibly).
77
78 There are many ways to get multiline data into a string. If you want it
79 to happen automatically while reading input, you'll want to set $/
80 (probably to '' for paragraphs or "undef" for the whole file) to allow
81 you to read more than one line at a time.
82
83 Read perlre to help you decide which of "/s" and "/m" (or both) you
84 might want to use: "/s" allows dot to include newline, and "/m" allows
85 caret and dollar to match next to a newline, not just at the end of the
86 string. You do need to make sure that you've actually got a multiline
87 string in there.
88
89 For example, this program detects duplicate words, even when they span
90 line breaks (but not paragraph ones). For this example, we don't need
91 "/s" because we aren't using dot in a regular expression that we want
92 to cross line boundaries. Neither do we need "/m" because we don't want
93 caret or dollar to match at any point inside the record next to
94 newlines. But it's imperative that $/ be set to something other than
95 the default, or else we won't actually ever have a multiline record
96 read in.
97
98 $/ = ''; # read in whole paragraph, not just one line
99 while ( <> ) {
100 while ( /\b([\w'-]+)(\s+\g1)+\b/gi ) { # word starts alpha
101 print "Duplicate $1 at paragraph $.\n";
102 }
103 }
104
105 Here's some code that finds sentences that begin with "From " (which
106 would be mangled by many mailers):
107
108 $/ = ''; # read in whole paragraph, not just one line
109 while ( <> ) {
110 while ( /^From /gm ) { # /m makes ^ match next to \n
111 print "leading From in paragraph $.\n";
112 }
113 }
114
115 Here's code that finds everything between START and END in a paragraph:
116
117 undef $/; # read in whole file, not just one line or paragraph
118 while ( <> ) {
119 while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
120 print "$1\n";
121 }
122 }
123
124 How can I pull out lines between two patterns that are themselves on
125 different lines?
126 You can use Perl's somewhat exotic ".." operator (documented in
127 perlop):
128
129 perl -ne 'print if /START/ .. /END/' file1 file2 ...
130
131 If you wanted text and not lines, you would use
132
133 perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
134
135 But if you want nested occurrences of "START" through "END", you'll run
136 up against the problem described in the question in this section on
137 matching balanced text.
138
139 Here's another example of using "..":
140
141 while (<>) {
142 my $in_header = 1 .. /^$/;
143 my $in_body = /^$/ .. eof;
144 # now choose between them
145 } continue {
146 $. = 0 if eof; # fix $.
147 }
148
149 How do I match XML, HTML, or other nasty, ugly things with a regex?
150 Do not use regexes. Use a module and forget about the regular
151 expressions. The XML::LibXML, HTML::TokeParser and HTML::TreeBuilder
152 modules are good starts, although each namespace has other parsing
153 modules specialized for certain tasks and different ways of doing it.
154 Start at CPAN Search ( <http://metacpan.org/> ) and wonder at all the
155 work people have done for you already! :)
156
157 I put a regular expression into $/ but it didn't work. What's wrong?
158 $/ has to be a string. You can use these examples if you really need to
159 do this.
160
161 If you have File::Stream, this is easy.
162
163 use File::Stream;
164
165 my $stream = File::Stream->new(
166 $filehandle,
167 separator => qr/\s*,\s*/,
168 );
169
170 print "$_\n" while <$stream>;
171
172 If you don't have File::Stream, you have to do a little more work.
173
174 You can use the four-argument form of sysread to continually add to a
175 buffer. After you add to the buffer, you check if you have a complete
176 line (using your regular expression).
177
178 local $_ = "";
179 while( sysread FH, $_, 8192, length ) {
180 while( s/^((?s).*?)your_pattern// ) {
181 my $record = $1;
182 # do stuff here.
183 }
184 }
185
186 You can do the same thing with foreach and a match using the c flag and
187 the \G anchor, if you do not mind your entire file being in memory at
188 the end.
189
190 local $_ = "";
191 while( sysread FH, $_, 8192, length ) {
192 foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
193 # do stuff here.
194 }
195 substr( $_, 0, pos ) = "" if pos;
196 }
197
198 How do I substitute case-insensitively on the LHS while preserving case on
199 the RHS?
200 Here's a lovely Perlish solution by Larry Rosler. It exploits
201 properties of bitwise xor on ASCII strings.
202
203 $_= "this is a TEsT case";
204
205 $old = 'test';
206 $new = 'success';
207
208 s{(\Q$old\E)}
209 { uc $new | (uc $1 ^ $1) .
210 (uc(substr $1, -1) ^ substr $1, -1) x
211 (length($new) - length $1)
212 }egi;
213
214 print;
215
216 And here it is as a subroutine, modeled after the above:
217
218 sub preserve_case {
219 my ($old, $new) = @_;
220 my $mask = uc $old ^ $old;
221
222 uc $new | $mask .
223 substr($mask, -1) x (length($new) - length($old))
224 }
225
226 $string = "this is a TEsT case";
227 $string =~ s/(test)/preserve_case($1, "success")/egi;
228 print "$string\n";
229
230 This prints:
231
232 this is a SUcCESS case
233
234 As an alternative, to keep the case of the replacement word if it is
235 longer than the original, you can use this code, by Jeff Pinyan:
236
237 sub preserve_case {
238 my ($from, $to) = @_;
239 my ($lf, $lt) = map length, @_;
240
241 if ($lt < $lf) { $from = substr $from, 0, $lt }
242 else { $from .= substr $to, $lf }
243
244 return uc $to | ($from ^ uc $from);
245 }
246
247 This changes the sentence to "this is a SUcCess case."
248
249 Just to show that C programmers can write C in any programming
250 language, if you prefer a more C-like solution, the following script
251 makes the substitution have the same case, letter by letter, as the
252 original. (It also happens to run about 240% slower than the Perlish
253 solution runs.) If the substitution has more characters than the
254 string being substituted, the case of the last character is used for
255 the rest of the substitution.
256
257 # Original by Nathan Torkington, massaged by Jeffrey Friedl
258 #
259 sub preserve_case
260 {
261 my ($old, $new) = @_;
262 my $state = 0; # 0 = no change; 1 = lc; 2 = uc
263 my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
264 my $len = $oldlen < $newlen ? $oldlen : $newlen;
265
266 for ($i = 0; $i < $len; $i++) {
267 if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
268 $state = 0;
269 } elsif (lc $c eq $c) {
270 substr($new, $i, 1) = lc(substr($new, $i, 1));
271 $state = 1;
272 } else {
273 substr($new, $i, 1) = uc(substr($new, $i, 1));
274 $state = 2;
275 }
276 }
277 # finish up with any remaining new (for when new is longer than old)
278 if ($newlen > $oldlen) {
279 if ($state == 1) {
280 substr($new, $oldlen) = lc(substr($new, $oldlen));
281 } elsif ($state == 2) {
282 substr($new, $oldlen) = uc(substr($new, $oldlen));
283 }
284 }
285 return $new;
286 }
287
288 How can I make "\w" match national character sets?
289 Put "use locale;" in your script. The \w character class is taken from
290 the current locale.
291
292 See perllocale for details.
293
294 How can I match a locale-smart version of "/[a-zA-Z]/"?
295 You can use the POSIX character class syntax "/[[:alpha:]]/" documented
296 in perlre.
297
298 No matter which locale you are in, the alphabetic characters are the
299 characters in \w without the digits and the underscore. As a regex,
300 that looks like "/[^\W\d_]/". Its complement, the non-alphabetics, is
301 then everything in \W along with the digits and the underscore, or
302 "/[\W\d_]/".
303
304 How can I quote a variable to use in a regex?
305 The Perl parser will expand $variable and @variable references in
306 regular expressions unless the delimiter is a single quote. Remember,
307 too, that the right-hand side of a "s///" substitution is considered a
308 double-quoted string (see perlop for more details). Remember also that
309 any regex special characters will be acted on unless you precede the
310 substitution with \Q. Here's an example:
311
312 $string = "Placido P. Octopus";
313 $regex = "P.";
314
315 $string =~ s/$regex/Polyp/;
316 # $string is now "Polypacido P. Octopus"
317
318 Because "." is special in regular expressions, and can match any single
319 character, the regex "P." here has matched the <Pl> in the original
320 string.
321
322 To escape the special meaning of ".", we use "\Q":
323
324 $string = "Placido P. Octopus";
325 $regex = "P.";
326
327 $string =~ s/\Q$regex/Polyp/;
328 # $string is now "Placido Polyp Octopus"
329
330 The use of "\Q" causes the "." in the regex to be treated as a regular
331 character, so that "P." matches a "P" followed by a dot.
332
333 What is "/o" really for?
334 (contributed by brian d foy)
335
336 The "/o" option for regular expressions (documented in perlop and
337 perlreref) tells Perl to compile the regular expression only once.
338 This is only useful when the pattern contains a variable. Perls 5.6 and
339 later handle this automatically if the pattern does not change.
340
341 Since the match operator "m//", the substitution operator "s///", and
342 the regular expression quoting operator "qr//" are double-quotish
343 constructs, you can interpolate variables into the pattern. See the
344 answer to "How can I quote a variable to use in a regex?" for more
345 details.
346
347 This example takes a regular expression from the argument list and
348 prints the lines of input that match it:
349
350 my $pattern = shift @ARGV;
351
352 while( <> ) {
353 print if m/$pattern/;
354 }
355
356 Versions of Perl prior to 5.6 would recompile the regular expression
357 for each iteration, even if $pattern had not changed. The "/o" would
358 prevent this by telling Perl to compile the pattern the first time,
359 then reuse that for subsequent iterations:
360
361 my $pattern = shift @ARGV;
362
363 while( <> ) {
364 print if m/$pattern/o; # useful for Perl < 5.6
365 }
366
367 In versions 5.6 and later, Perl won't recompile the regular expression
368 if the variable hasn't changed, so you probably don't need the "/o"
369 option. It doesn't hurt, but it doesn't help either. If you want any
370 version of Perl to compile the regular expression only once even if the
371 variable changes (thus, only using its initial value), you still need
372 the "/o".
373
374 You can watch Perl's regular expression engine at work to verify for
375 yourself if Perl is recompiling a regular expression. The "use re
376 'debug'" pragma (comes with Perl 5.005 and later) shows the details.
377 With Perls before 5.6, you should see "re" reporting that its compiling
378 the regular expression on each iteration. With Perl 5.6 or later, you
379 should only see "re" report that for the first iteration.
380
381 use re 'debug';
382
383 my $regex = 'Perl';
384 foreach ( qw(Perl Java Ruby Python) ) {
385 print STDERR "-" x 73, "\n";
386 print STDERR "Trying $_...\n";
387 print STDERR "\t$_ is good!\n" if m/$regex/;
388 }
389
390 How do I use a regular expression to strip C-style comments from a file?
391 While this actually can be done, it's much harder than you'd think.
392 For example, this one-liner
393
394 perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
395
396 will work in many but not all cases. You see, it's too simple-minded
397 for certain kinds of C programs, in particular, those with what appear
398 to be comments in quoted strings. For that, you'd need something like
399 this, created by Jeffrey Friedl and later modified by Fred Curtis.
400
401 $/ = undef;
402 $_ = <>;
403 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
404 print;
405
406 This could, of course, be more legibly written with the "/x" modifier,
407 adding whitespace and comments. Here it is expanded, courtesy of Fred
408 Curtis.
409
410 s{
411 /\* ## Start of /* ... */ comment
412 [^*]*\*+ ## Non-* followed by 1-or-more *'s
413 (
414 [^/*][^*]*\*+
415 )* ## 0-or-more things which don't start with /
416 ## but do end with '*'
417 / ## End of /* ... */ comment
418
419 | ## OR various things which aren't comments:
420
421 (
422 " ## Start of " ... " string
423 (
424 \\. ## Escaped char
425 | ## OR
426 [^"\\] ## Non "\
427 )*
428 " ## End of " ... " string
429
430 | ## OR
431
432 ' ## Start of ' ... ' string
433 (
434 \\. ## Escaped char
435 | ## OR
436 [^'\\] ## Non '\
437 )*
438 ' ## End of ' ... ' string
439
440 | ## OR
441
442 . ## Anything other char
443 [^/"'\\]* ## Chars which doesn't start a comment, string or escape
444 )
445 }{defined $2 ? $2 : ""}gxse;
446
447 A slight modification also removes C++ comments, possibly spanning
448 multiple lines using a continuation character:
449
450 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $3 ? $3 : ""#gse;
451
452 Can I use Perl regular expressions to match balanced text?
453 (contributed by brian d foy)
454
455 Your first try should probably be the Text::Balanced module, which is
456 in the Perl standard library since Perl 5.8. It has a variety of
457 functions to deal with tricky text. The Regexp::Common module can also
458 help by providing canned patterns you can use.
459
460 As of Perl 5.10, you can match balanced text with regular expressions
461 using recursive patterns. Before Perl 5.10, you had to resort to
462 various tricks such as using Perl code in "(??{})" sequences.
463
464 Here's an example using a recursive regular expression. The goal is to
465 capture all of the text within angle brackets, including the text in
466 nested angle brackets. This sample text has two "major" groups: a group
467 with one level of nesting and a group with two levels of nesting. There
468 are five total groups in angle brackets:
469
470 I have some <brackets in <nested brackets> > and
471 <another group <nested once <nested twice> > >
472 and that's it.
473
474 The regular expression to match the balanced text uses two new (to Perl
475 5.10) regular expression features. These are covered in perlre and this
476 example is a modified version of one in that documentation.
477
478 First, adding the new possessive "+" to any quantifier finds the
479 longest match and does not backtrack. That's important since you want
480 to handle any angle brackets through the recursion, not backtracking.
481 The group "[^<>]++" finds one or more non-angle brackets without
482 backtracking.
483
484 Second, the new "(?PARNO)" refers to the sub-pattern in the particular
485 capture group given by "PARNO". In the following regex, the first
486 capture group finds (and remembers) the balanced text, and you need
487 that same pattern within the first buffer to get past the nested text.
488 That's the recursive part. The "(?1)" uses the pattern in the outer
489 capture group as an independent part of the regex.
490
491 Putting it all together, you have:
492
493 #!/usr/local/bin/perl5.10.0
494
495 my $string =<<"HERE";
496 I have some <brackets in <nested brackets> > and
497 <another group <nested once <nested twice> > >
498 and that's it.
499 HERE
500
501 my @groups = $string =~ m/
502 ( # start of capture group 1
503 < # match an opening angle bracket
504 (?:
505 [^<>]++ # one or more non angle brackets, non backtracking
506 |
507 (?1) # found < or >, so recurse to capture group 1
508 )*
509 > # match a closing angle bracket
510 ) # end of capture group 1
511 /xg;
512
513 $" = "\n\t";
514 print "Found:\n\t@groups\n";
515
516 The output shows that Perl found the two major groups:
517
518 Found:
519 <brackets in <nested brackets> >
520 <another group <nested once <nested twice> > >
521
522 With a little extra work, you can get all of the groups in angle
523 brackets even if they are in other angle brackets too. Each time you
524 get a balanced match, remove its outer delimiter (that's the one you
525 just matched so don't match it again) and add it to a queue of strings
526 to process. Keep doing that until you get no matches:
527
528 #!/usr/local/bin/perl5.10.0
529
530 my @queue =<<"HERE";
531 I have some <brackets in <nested brackets> > and
532 <another group <nested once <nested twice> > >
533 and that's it.
534 HERE
535
536 my $regex = qr/
537 ( # start of bracket 1
538 < # match an opening angle bracket
539 (?:
540 [^<>]++ # one or more non angle brackets, non backtracking
541 |
542 (?1) # recurse to bracket 1
543 )*
544 > # match a closing angle bracket
545 ) # end of bracket 1
546 /x;
547
548 $" = "\n\t";
549
550 while( @queue ) {
551 my $string = shift @queue;
552
553 my @groups = $string =~ m/$regex/g;
554 print "Found:\n\t@groups\n\n" if @groups;
555
556 unshift @queue, map { s/^<//; s/>$//; $_ } @groups;
557 }
558
559 The output shows all of the groups. The outermost matches show up first
560 and the nested matches show up later:
561
562 Found:
563 <brackets in <nested brackets> >
564 <another group <nested once <nested twice> > >
565
566 Found:
567 <nested brackets>
568
569 Found:
570 <nested once <nested twice> >
571
572 Found:
573 <nested twice>
574
575 What does it mean that regexes are greedy? How can I get around it?
576 Most people mean that greedy regexes match as much as they can.
577 Technically speaking, it's actually the quantifiers ("?", "*", "+",
578 "{}") that are greedy rather than the whole pattern; Perl prefers local
579 greed and immediate gratification to overall greed. To get non-greedy
580 versions of the same quantifiers, use ("??", "*?", "+?", "{}?").
581
582 An example:
583
584 my $s1 = my $s2 = "I am very very cold";
585 $s1 =~ s/ve.*y //; # I am cold
586 $s2 =~ s/ve.*?y //; # I am very cold
587
588 Notice how the second substitution stopped matching as soon as it
589 encountered "y ". The "*?" quantifier effectively tells the regular
590 expression engine to find a match as quickly as possible and pass
591 control on to whatever is next in line, as you would if you were
592 playing hot potato.
593
594 How do I process each word on each line?
595 Use the split function:
596
597 while (<>) {
598 foreach my $word ( split ) {
599 # do something with $word here
600 }
601 }
602
603 Note that this isn't really a word in the English sense; it's just
604 chunks of consecutive non-whitespace characters.
605
606 To work with only alphanumeric sequences (including underscores), you
607 might consider
608
609 while (<>) {
610 foreach $word (m/(\w+)/g) {
611 # do something with $word here
612 }
613 }
614
615 How can I print out a word-frequency or line-frequency summary?
616 To do this, you have to parse out each word in the input stream. We'll
617 pretend that by word you mean chunk of alphabetics, hyphens, or
618 apostrophes, rather than the non-whitespace chunk idea of a word given
619 in the previous question:
620
621 my (%seen);
622 while (<>) {
623 while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
624 $seen{$1}++;
625 }
626 }
627
628 while ( my ($word, $count) = each %seen ) {
629 print "$count $word\n";
630 }
631
632 If you wanted to do the same thing for lines, you wouldn't need a
633 regular expression:
634
635 my (%seen);
636
637 while (<>) {
638 $seen{$_}++;
639 }
640
641 while ( my ($line, $count) = each %seen ) {
642 print "$count $line";
643 }
644
645 If you want these output in a sorted order, see perlfaq4: "How do I
646 sort a hash (optionally by value instead of key)?".
647
648 How can I do approximate matching?
649 See the module String::Approx available from CPAN.
650
651 How do I efficiently match many regular expressions at once?
652 (contributed by brian d foy)
653
654 You want to avoid compiling a regular expression every time you want to
655 match it. In this example, perl must recompile the regular expression
656 for every iteration of the "foreach" loop since $pattern can change:
657
658 my @patterns = qw( fo+ ba[rz] );
659
660 LINE: while( my $line = <> ) {
661 foreach my $pattern ( @patterns ) {
662 if( $line =~ m/\b$pattern\b/i ) {
663 print $line;
664 next LINE;
665 }
666 }
667 }
668
669 The "qr//" operator compiles a regular expression, but doesn't apply
670 it. When you use the pre-compiled version of the regex, perl does less
671 work. In this example, I inserted a "map" to turn each pattern into its
672 pre-compiled form. The rest of the script is the same, but faster:
673
674 my @patterns = map { qr/\b$_\b/i } qw( fo+ ba[rz] );
675
676 LINE: while( my $line = <> ) {
677 foreach my $pattern ( @patterns ) {
678 if( $line =~ m/$pattern/ ) {
679 print $line;
680 next LINE;
681 }
682 }
683 }
684
685 In some cases, you may be able to make several patterns into a single
686 regular expression. Beware of situations that require backtracking
687 though. In this example, the regex is only compiled once because $regex
688 doesn't change between iterations:
689
690 my $regex = join '|', qw( fo+ ba[rz] );
691
692 while( my $line = <> ) {
693 print if $line =~ m/\b(?:$regex)\b/i;
694 }
695
696 The function "list2re" in Data::Munge on CPAN can also be used to form
697 a single regex that matches a list of literal strings (not regexes).
698
699 For more details on regular expression efficiency, see Mastering
700 Regular Expressions by Jeffrey Friedl. He explains how the regular
701 expressions engine works and why some patterns are surprisingly
702 inefficient. Once you understand how perl applies regular expressions,
703 you can tune them for individual situations.
704
705 Why don't word-boundary searches with "\b" work for me?
706 (contributed by brian d foy)
707
708 Ensure that you know what \b really does: it's the boundary between a
709 word character, \w, and something that isn't a word character. That
710 thing that isn't a word character might be \W, but it can also be the
711 start or end of the string.
712
713 It's not (not!) the boundary between whitespace and non-whitespace, and
714 it's not the stuff between words we use to create sentences.
715
716 In regex speak, a word boundary (\b) is a "zero width assertion",
717 meaning that it doesn't represent a character in the string, but a
718 condition at a certain position.
719
720 For the regular expression, /\bPerl\b/, there has to be a word boundary
721 before the "P" and after the "l". As long as something other than a
722 word character precedes the "P" and succeeds the "l", the pattern will
723 match. These strings match /\bPerl\b/.
724
725 "Perl" # no word char before "P" or after "l"
726 "Perl " # same as previous (space is not a word char)
727 "'Perl'" # the "'" char is not a word char
728 "Perl's" # no word char before "P", non-word char after "l"
729
730 These strings do not match /\bPerl\b/.
731
732 "Perl_" # "_" is a word char!
733 "Perler" # no word char before "P", but one after "l"
734
735 You don't have to use \b to match words though. You can look for non-
736 word characters surrounded by word characters. These strings match the
737 pattern /\b'\b/.
738
739 "don't" # the "'" char is surrounded by "n" and "t"
740 "qep'a'" # the "'" char is surrounded by "p" and "a"
741
742 These strings do not match /\b'\b/.
743
744 "foo'" # there is no word char after non-word "'"
745
746 You can also use the complement of \b, \B, to specify that there should
747 not be a word boundary.
748
749 In the pattern /\Bam\B/, there must be a word character before the "a"
750 and after the "m". These patterns match /\Bam\B/:
751
752 "llama" # "am" surrounded by word chars
753 "Samuel" # same
754
755 These strings do not match /\Bam\B/
756
757 "Sam" # no word boundary before "a", but one after "m"
758 "I am Sam" # "am" surrounded by non-word chars
759
760 Why does using $&, $`, or $' slow my program down?
761 (contributed by Anno Siegel)
762
763 Once Perl sees that you need one of these variables anywhere in the
764 program, it provides them on each and every pattern match. That means
765 that on every pattern match the entire string will be copied, part of
766 it to $`, part to $&, and part to $'. Thus the penalty is most severe
767 with long strings and patterns that match often. Avoid $&, $', and $`
768 if you can, but if you can't, once you've used them at all, use them at
769 will because you've already paid the price. Remember that some
770 algorithms really appreciate them. As of the 5.005 release, the $&
771 variable is no longer "expensive" the way the other two are.
772
773 Since Perl 5.6.1 the special variables @- and @+ can functionally
774 replace $`, $& and $'. These arrays contain pointers to the beginning
775 and end of each match (see perlvar for the full story), so they give
776 you essentially the same information, but without the risk of excessive
777 string copying.
778
779 Perl 5.10 added three specials, "${^MATCH}", "${^PREMATCH}", and
780 "${^POSTMATCH}" to do the same job but without the global performance
781 penalty. Perl 5.10 only sets these variables if you compile or execute
782 the regular expression with the "/p" modifier.
783
784 What good is "\G" in a regular expression?
785 You use the "\G" anchor to start the next match on the same string
786 where the last match left off. The regular expression engine cannot
787 skip over any characters to find the next match with this anchor, so
788 "\G" is similar to the beginning of string anchor, "^". The "\G" anchor
789 is typically used with the "g" modifier. It uses the value of "pos()"
790 as the position to start the next match. As the match operator makes
791 successive matches, it updates "pos()" with the position of the next
792 character past the last match (or the first character of the next
793 match, depending on how you like to look at it). Each string has its
794 own "pos()" value.
795
796 Suppose you want to match all of consecutive pairs of digits in a
797 string like "1122a44" and stop matching when you encounter non-digits.
798 You want to match 11 and 22 but the letter "a" shows up between 22 and
799 44 and you want to stop at "a". Simply matching pairs of digits skips
800 over the "a" and still matches 44.
801
802 $_ = "1122a44";
803 my @pairs = m/(\d\d)/g; # qw( 11 22 44 )
804
805 If you use the "\G" anchor, you force the match after 22 to start with
806 the "a". The regular expression cannot match there since it does not
807 find a digit, so the next match fails and the match operator returns
808 the pairs it already found.
809
810 $_ = "1122a44";
811 my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
812
813 You can also use the "\G" anchor in scalar context. You still need the
814 "g" modifier.
815
816 $_ = "1122a44";
817 while( m/\G(\d\d)/g ) {
818 print "Found $1\n";
819 }
820
821 After the match fails at the letter "a", perl resets "pos()" and the
822 next match on the same string starts at the beginning.
823
824 $_ = "1122a44";
825 while( m/\G(\d\d)/g ) {
826 print "Found $1\n";
827 }
828
829 print "Found $1 after while" if m/(\d\d)/g; # finds "11"
830
831 You can disable "pos()" resets on fail with the "c" modifier,
832 documented in perlop and perlreref. Subsequent matches start where the
833 last successful match ended (the value of "pos()") even if a match on
834 the same string has failed in the meantime. In this case, the match
835 after the "while()" loop starts at the "a" (where the last match
836 stopped), and since it does not use any anchor it can skip over the "a"
837 to find 44.
838
839 $_ = "1122a44";
840 while( m/\G(\d\d)/gc ) {
841 print "Found $1\n";
842 }
843
844 print "Found $1 after while" if m/(\d\d)/g; # finds "44"
845
846 Typically you use the "\G" anchor with the "c" modifier when you want
847 to try a different match if one fails, such as in a tokenizer. Jeffrey
848 Friedl offers this example which works in 5.004 or later.
849
850 while (<>) {
851 chomp;
852 PARSER: {
853 m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; };
854 m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; };
855 m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; };
856 m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; };
857 }
858 }
859
860 For each line, the "PARSER" loop first tries to match a series of
861 digits followed by a word boundary. This match has to start at the
862 place the last match left off (or the beginning of the string on the
863 first match). Since "m/ \G( \d+\b )/gcx" uses the "c" modifier, if the
864 string does not match that regular expression, perl does not reset
865 pos() and the next match starts at the same position to try a different
866 pattern.
867
868 Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
869 While it's true that Perl's regular expressions resemble the DFAs
870 (deterministic finite automata) of the egrep(1) program, they are in
871 fact implemented as NFAs (non-deterministic finite automata) to allow
872 backtracking and backreferencing. And they aren't POSIX-style either,
873 because those guarantee worst-case behavior for all cases. (It seems
874 that some people prefer guarantees of consistency, even when what's
875 guaranteed is slowness.) See the book "Mastering Regular Expressions"
876 (from O'Reilly) by Jeffrey Friedl for all the details you could ever
877 hope to know on these matters (a full citation appears in perlfaq2).
878
879 What's wrong with using grep in a void context?
880 The problem is that grep builds a return list, regardless of the
881 context. This means you're making Perl go to the trouble of building a
882 list that you then just throw away. If the list is large, you waste
883 both time and space. If your intent is to iterate over the list, then
884 use a for loop for this purpose.
885
886 In perls older than 5.8.1, map suffers from this problem as well. But
887 since 5.8.1, this has been fixed, and map is context aware - in void
888 context, no lists are constructed.
889
890 How can I match strings with multibyte characters?
891 Starting from Perl 5.6 Perl has had some level of multibyte character
892 support. Perl 5.8 or later is recommended. Supported multibyte
893 character repertoires include Unicode, and legacy encodings through the
894 Encode module. See perluniintro, perlunicode, and Encode.
895
896 If you are stuck with older Perls, you can do Unicode with the
897 Unicode::String module, and character conversions using the
898 Unicode::Map8 and Unicode::Map modules. If you are using Japanese
899 encodings, you might try using the jperl 5.005_03.
900
901 Finally, the following set of approaches was offered by Jeffrey Friedl,
902 whose article in issue #5 of The Perl Journal talks about this very
903 matter.
904
905 Let's suppose you have some weird Martian encoding where pairs of ASCII
906 uppercase letters encode single Martian letters (i.e. the two bytes
907 "CV" make a single Martian letter, as do the two bytes "SG", "VS",
908 "XX", etc.). Other bytes represent single characters, just like ASCII.
909
910 So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
911 nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
912
913 Now, say you want to search for the single character "/GX/". Perl
914 doesn't know about Martian, so it'll find the two bytes "GX" in the "I
915 am CVSGXX!" string, even though that character isn't there: it just
916 looks like it is because "SG" is next to "XX", but there's no real
917 "GX". This is a big problem.
918
919 Here are a few ways, all painful, to deal with it:
920
921 # Make sure adjacent "martian" bytes are no longer adjacent.
922 $martian =~ s/([A-Z][A-Z])/ $1 /g;
923
924 print "found GX!\n" if $martian =~ /GX/;
925
926 Or like this:
927
928 my @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
929 # above is conceptually similar to: my @chars = $text =~ m/(.)/g;
930 #
931 foreach my $char (@chars) {
932 print "found GX!\n", last if $char eq 'GX';
933 }
934
935 Or like this:
936
937 while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
938 if ($1 eq 'GX') {
939 print "found GX!\n";
940 last;
941 }
942 }
943
944 Here's another, slightly less painful, way to do it from Benjamin
945 Goldberg, who uses a zero-width negative look-behind assertion.
946
947 print "found GX!\n" if $martian =~ m/
948 (?<![A-Z])
949 (?:[A-Z][A-Z])*?
950 GX
951 /x;
952
953 This succeeds if the "martian" character GX is in the string, and fails
954 otherwise. If you don't like using (?<!), a zero-width negative look-
955 behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
956
957 It does have the drawback of putting the wrong thing in $-[0] and
958 $+[0], but this usually can be worked around.
959
960 How do I match a regular expression that's in a variable?
961 (contributed by brian d foy)
962
963 We don't have to hard-code patterns into the match operator (or
964 anything else that works with regular expressions). We can put the
965 pattern in a variable for later use.
966
967 The match operator is a double quote context, so you can interpolate
968 your variable just like a double quoted string. In this case, you read
969 the regular expression as user input and store it in $regex. Once you
970 have the pattern in $regex, you use that variable in the match
971 operator.
972
973 chomp( my $regex = <STDIN> );
974
975 if( $string =~ m/$regex/ ) { ... }
976
977 Any regular expression special characters in $regex are still special,
978 and the pattern still has to be valid or Perl will complain. For
979 instance, in this pattern there is an unpaired parenthesis.
980
981 my $regex = "Unmatched ( paren";
982
983 "Two parens to bind them all" =~ m/$regex/;
984
985 When Perl compiles the regular expression, it treats the parenthesis as
986 the start of a memory match. When it doesn't find the closing
987 parenthesis, it complains:
988
989 Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE paren/ at script line 3.
990
991 You can get around this in several ways depending on our situation.
992 First, if you don't want any of the characters in the string to be
993 special, you can escape them with "quotemeta" before you use the
994 string.
995
996 chomp( my $regex = <STDIN> );
997 $regex = quotemeta( $regex );
998
999 if( $string =~ m/$regex/ ) { ... }
1000
1001 You can also do this directly in the match operator using the "\Q" and
1002 "\E" sequences. The "\Q" tells Perl where to start escaping special
1003 characters, and the "\E" tells it where to stop (see perlop for more
1004 details).
1005
1006 chomp( my $regex = <STDIN> );
1007
1008 if( $string =~ m/\Q$regex\E/ ) { ... }
1009
1010 Alternately, you can use "qr//", the regular expression quote operator
1011 (see perlop for more details). It quotes and perhaps compiles the
1012 pattern, and you can apply regular expression flags to the pattern.
1013
1014 chomp( my $input = <STDIN> );
1015
1016 my $regex = qr/$input/is;
1017
1018 $string =~ m/$regex/ # same as m/$input/is;
1019
1020 You might also want to trap any errors by wrapping an "eval" block
1021 around the whole thing.
1022
1023 chomp( my $input = <STDIN> );
1024
1025 eval {
1026 if( $string =~ m/\Q$input\E/ ) { ... }
1027 };
1028 warn $@ if $@;
1029
1030 Or...
1031
1032 my $regex = eval { qr/$input/is };
1033 if( defined $regex ) {
1034 $string =~ m/$regex/;
1035 }
1036 else {
1037 warn $@;
1038 }
1039
1041 Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1042 authors as noted. All rights reserved.
1043
1044 This documentation is free; you can redistribute it and/or modify it
1045 under the same terms as Perl itself.
1046
1047 Irrespective of its distribution, all code examples in this file are
1048 hereby placed into the public domain. You are permitted and encouraged
1049 to use this code in your own programs for fun or for profit as you see
1050 fit. A simple comment in the code giving credit would be courteous but
1051 is not required.
1052
1053
1054
1055perl v5.36.0 2022-07-22 perlfaq6(3)