1perlfaq6(3) User Contributed Perl Documentation perlfaq6(3)
2
3
4
6 perlfaq6 - Regular Expressions
7
9 version 5.20190126
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 If you have Perl 5.10 or later, this is almost trivial. You just smart
655 match against an array of regular expression objects:
656
657 my @patterns = ( qr/Fr.d/, qr/B.rn.y/, qr/W.lm./ );
658
659 if( $string ~~ @patterns ) {
660 ...
661 };
662
663 The smart match stops when it finds a match, so it doesn't have to try
664 every expression.
665
666 Earlier than Perl 5.10, you have a bit of work to do. You want to avoid
667 compiling a regular expression every time you want to match it. In
668 this example, perl must recompile the regular expression for every
669 iteration of the "foreach" loop since it has no way to know what
670 $pattern will be:
671
672 my @patterns = qw( foo bar baz );
673
674 LINE: while( <DATA> ) {
675 foreach $pattern ( @patterns ) {
676 if( /\b$pattern\b/i ) {
677 print;
678 next LINE;
679 }
680 }
681 }
682
683 The "qr//" operator showed up in perl 5.005. It compiles a regular
684 expression, but doesn't apply it. When you use the pre-compiled version
685 of the regex, perl does less work. In this example, I inserted a "map"
686 to turn each pattern into its pre-compiled form. The rest of the script
687 is the same, but faster:
688
689 my @patterns = map { qr/\b$_\b/i } qw( foo bar baz );
690
691 LINE: while( <> ) {
692 foreach $pattern ( @patterns ) {
693 if( /$pattern/ ) {
694 print;
695 next LINE;
696 }
697 }
698 }
699
700 In some cases, you may be able to make several patterns into a single
701 regular expression. Beware of situations that require backtracking
702 though.
703
704 my $regex = join '|', qw( foo bar baz );
705
706 LINE: while( <> ) {
707 print if /\b(?:$regex)\b/i;
708 }
709
710 For more details on regular expression efficiency, see Mastering
711 Regular Expressions by Jeffrey Friedl. He explains how the regular
712 expressions engine works and why some patterns are surprisingly
713 inefficient. Once you understand how perl applies regular expressions,
714 you can tune them for individual situations.
715
716 Why don't word-boundary searches with "\b" work for me?
717 (contributed by brian d foy)
718
719 Ensure that you know what \b really does: it's the boundary between a
720 word character, \w, and something that isn't a word character. That
721 thing that isn't a word character might be \W, but it can also be the
722 start or end of the string.
723
724 It's not (not!) the boundary between whitespace and non-whitespace, and
725 it's not the stuff between words we use to create sentences.
726
727 In regex speak, a word boundary (\b) is a "zero width assertion",
728 meaning that it doesn't represent a character in the string, but a
729 condition at a certain position.
730
731 For the regular expression, /\bPerl\b/, there has to be a word boundary
732 before the "P" and after the "l". As long as something other than a
733 word character precedes the "P" and succeeds the "l", the pattern will
734 match. These strings match /\bPerl\b/.
735
736 "Perl" # no word char before "P" or after "l"
737 "Perl " # same as previous (space is not a word char)
738 "'Perl'" # the "'" char is not a word char
739 "Perl's" # no word char before "P", non-word char after "l"
740
741 These strings do not match /\bPerl\b/.
742
743 "Perl_" # "_" is a word char!
744 "Perler" # no word char before "P", but one after "l"
745
746 You don't have to use \b to match words though. You can look for non-
747 word characters surrounded by word characters. These strings match the
748 pattern /\b'\b/.
749
750 "don't" # the "'" char is surrounded by "n" and "t"
751 "qep'a'" # the "'" char is surrounded by "p" and "a"
752
753 These strings do not match /\b'\b/.
754
755 "foo'" # there is no word char after non-word "'"
756
757 You can also use the complement of \b, \B, to specify that there should
758 not be a word boundary.
759
760 In the pattern /\Bam\B/, there must be a word character before the "a"
761 and after the "m". These patterns match /\Bam\B/:
762
763 "llama" # "am" surrounded by word chars
764 "Samuel" # same
765
766 These strings do not match /\Bam\B/
767
768 "Sam" # no word boundary before "a", but one after "m"
769 "I am Sam" # "am" surrounded by non-word chars
770
771 Why does using $&, $`, or $' slow my program down?
772 (contributed by Anno Siegel)
773
774 Once Perl sees that you need one of these variables anywhere in the
775 program, it provides them on each and every pattern match. That means
776 that on every pattern match the entire string will be copied, part of
777 it to $`, part to $&, and part to $'. Thus the penalty is most severe
778 with long strings and patterns that match often. Avoid $&, $', and $`
779 if you can, but if you can't, once you've used them at all, use them at
780 will because you've already paid the price. Remember that some
781 algorithms really appreciate them. As of the 5.005 release, the $&
782 variable is no longer "expensive" the way the other two are.
783
784 Since Perl 5.6.1 the special variables @- and @+ can functionally
785 replace $`, $& and $'. These arrays contain pointers to the beginning
786 and end of each match (see perlvar for the full story), so they give
787 you essentially the same information, but without the risk of excessive
788 string copying.
789
790 Perl 5.10 added three specials, "${^MATCH}", "${^PREMATCH}", and
791 "${^POSTMATCH}" to do the same job but without the global performance
792 penalty. Perl 5.10 only sets these variables if you compile or execute
793 the regular expression with the "/p" modifier.
794
795 What good is "\G" in a regular expression?
796 You use the "\G" anchor to start the next match on the same string
797 where the last match left off. The regular expression engine cannot
798 skip over any characters to find the next match with this anchor, so
799 "\G" is similar to the beginning of string anchor, "^". The "\G" anchor
800 is typically used with the "g" modifier. It uses the value of "pos()"
801 as the position to start the next match. As the match operator makes
802 successive matches, it updates "pos()" with the position of the next
803 character past the last match (or the first character of the next
804 match, depending on how you like to look at it). Each string has its
805 own "pos()" value.
806
807 Suppose you want to match all of consecutive pairs of digits in a
808 string like "1122a44" and stop matching when you encounter non-digits.
809 You want to match 11 and 22 but the letter "a" shows up between 22 and
810 44 and you want to stop at "a". Simply matching pairs of digits skips
811 over the "a" and still matches 44.
812
813 $_ = "1122a44";
814 my @pairs = m/(\d\d)/g; # qw( 11 22 44 )
815
816 If you use the "\G" anchor, you force the match after 22 to start with
817 the "a". The regular expression cannot match there since it does not
818 find a digit, so the next match fails and the match operator returns
819 the pairs it already found.
820
821 $_ = "1122a44";
822 my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
823
824 You can also use the "\G" anchor in scalar context. You still need the
825 "g" modifier.
826
827 $_ = "1122a44";
828 while( m/\G(\d\d)/g ) {
829 print "Found $1\n";
830 }
831
832 After the match fails at the letter "a", perl resets "pos()" and the
833 next match on the same string starts at the beginning.
834
835 $_ = "1122a44";
836 while( m/\G(\d\d)/g ) {
837 print "Found $1\n";
838 }
839
840 print "Found $1 after while" if m/(\d\d)/g; # finds "11"
841
842 You can disable "pos()" resets on fail with the "c" modifier,
843 documented in perlop and perlreref. Subsequent matches start where the
844 last successful match ended (the value of "pos()") even if a match on
845 the same string has failed in the meantime. In this case, the match
846 after the "while()" loop starts at the "a" (where the last match
847 stopped), and since it does not use any anchor it can skip over the "a"
848 to find 44.
849
850 $_ = "1122a44";
851 while( m/\G(\d\d)/gc ) {
852 print "Found $1\n";
853 }
854
855 print "Found $1 after while" if m/(\d\d)/g; # finds "44"
856
857 Typically you use the "\G" anchor with the "c" modifier when you want
858 to try a different match if one fails, such as in a tokenizer. Jeffrey
859 Friedl offers this example which works in 5.004 or later.
860
861 while (<>) {
862 chomp;
863 PARSER: {
864 m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; };
865 m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; };
866 m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; };
867 m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; };
868 }
869 }
870
871 For each line, the "PARSER" loop first tries to match a series of
872 digits followed by a word boundary. This match has to start at the
873 place the last match left off (or the beginning of the string on the
874 first match). Since "m/ \G( \d+\b )/gcx" uses the "c" modifier, if the
875 string does not match that regular expression, perl does not reset
876 pos() and the next match starts at the same position to try a different
877 pattern.
878
879 Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
880 While it's true that Perl's regular expressions resemble the DFAs
881 (deterministic finite automata) of the egrep(1) program, they are in
882 fact implemented as NFAs (non-deterministic finite automata) to allow
883 backtracking and backreferencing. And they aren't POSIX-style either,
884 because those guarantee worst-case behavior for all cases. (It seems
885 that some people prefer guarantees of consistency, even when what's
886 guaranteed is slowness.) See the book "Mastering Regular Expressions"
887 (from O'Reilly) by Jeffrey Friedl for all the details you could ever
888 hope to know on these matters (a full citation appears in perlfaq2).
889
890 What's wrong with using grep in a void context?
891 The problem is that grep builds a return list, regardless of the
892 context. This means you're making Perl go to the trouble of building a
893 list that you then just throw away. If the list is large, you waste
894 both time and space. If your intent is to iterate over the list, then
895 use a for loop for this purpose.
896
897 In perls older than 5.8.1, map suffers from this problem as well. But
898 since 5.8.1, this has been fixed, and map is context aware - in void
899 context, no lists are constructed.
900
901 How can I match strings with multibyte characters?
902 Starting from Perl 5.6 Perl has had some level of multibyte character
903 support. Perl 5.8 or later is recommended. Supported multibyte
904 character repertoires include Unicode, and legacy encodings through the
905 Encode module. See perluniintro, perlunicode, and Encode.
906
907 If you are stuck with older Perls, you can do Unicode with the
908 Unicode::String module, and character conversions using the
909 Unicode::Map8 and Unicode::Map modules. If you are using Japanese
910 encodings, you might try using the jperl 5.005_03.
911
912 Finally, the following set of approaches was offered by Jeffrey Friedl,
913 whose article in issue #5 of The Perl Journal talks about this very
914 matter.
915
916 Let's suppose you have some weird Martian encoding where pairs of ASCII
917 uppercase letters encode single Martian letters (i.e. the two bytes
918 "CV" make a single Martian letter, as do the two bytes "SG", "VS",
919 "XX", etc.). Other bytes represent single characters, just like ASCII.
920
921 So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
922 nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
923
924 Now, say you want to search for the single character "/GX/". Perl
925 doesn't know about Martian, so it'll find the two bytes "GX" in the "I
926 am CVSGXX!" string, even though that character isn't there: it just
927 looks like it is because "SG" is next to "XX", but there's no real
928 "GX". This is a big problem.
929
930 Here are a few ways, all painful, to deal with it:
931
932 # Make sure adjacent "martian" bytes are no longer adjacent.
933 $martian =~ s/([A-Z][A-Z])/ $1 /g;
934
935 print "found GX!\n" if $martian =~ /GX/;
936
937 Or like this:
938
939 my @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
940 # above is conceptually similar to: my @chars = $text =~ m/(.)/g;
941 #
942 foreach my $char (@chars) {
943 print "found GX!\n", last if $char eq 'GX';
944 }
945
946 Or like this:
947
948 while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
949 if ($1 eq 'GX') {
950 print "found GX!\n";
951 last;
952 }
953 }
954
955 Here's another, slightly less painful, way to do it from Benjamin
956 Goldberg, who uses a zero-width negative look-behind assertion.
957
958 print "found GX!\n" if $martian =~ m/
959 (?<![A-Z])
960 (?:[A-Z][A-Z])*?
961 GX
962 /x;
963
964 This succeeds if the "martian" character GX is in the string, and fails
965 otherwise. If you don't like using (?<!), a zero-width negative look-
966 behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
967
968 It does have the drawback of putting the wrong thing in $-[0] and
969 $+[0], but this usually can be worked around.
970
971 How do I match a regular expression that's in a variable?
972 (contributed by brian d foy)
973
974 We don't have to hard-code patterns into the match operator (or
975 anything else that works with regular expressions). We can put the
976 pattern in a variable for later use.
977
978 The match operator is a double quote context, so you can interpolate
979 your variable just like a double quoted string. In this case, you read
980 the regular expression as user input and store it in $regex. Once you
981 have the pattern in $regex, you use that variable in the match
982 operator.
983
984 chomp( my $regex = <STDIN> );
985
986 if( $string =~ m/$regex/ ) { ... }
987
988 Any regular expression special characters in $regex are still special,
989 and the pattern still has to be valid or Perl will complain. For
990 instance, in this pattern there is an unpaired parenthesis.
991
992 my $regex = "Unmatched ( paren";
993
994 "Two parens to bind them all" =~ m/$regex/;
995
996 When Perl compiles the regular expression, it treats the parenthesis as
997 the start of a memory match. When it doesn't find the closing
998 parenthesis, it complains:
999
1000 Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE paren/ at script line 3.
1001
1002 You can get around this in several ways depending on our situation.
1003 First, if you don't want any of the characters in the string to be
1004 special, you can escape them with "quotemeta" before you use the
1005 string.
1006
1007 chomp( my $regex = <STDIN> );
1008 $regex = quotemeta( $regex );
1009
1010 if( $string =~ m/$regex/ ) { ... }
1011
1012 You can also do this directly in the match operator using the "\Q" and
1013 "\E" sequences. The "\Q" tells Perl where to start escaping special
1014 characters, and the "\E" tells it where to stop (see perlop for more
1015 details).
1016
1017 chomp( my $regex = <STDIN> );
1018
1019 if( $string =~ m/\Q$regex\E/ ) { ... }
1020
1021 Alternately, you can use "qr//", the regular expression quote operator
1022 (see perlop for more details). It quotes and perhaps compiles the
1023 pattern, and you can apply regular expression flags to the pattern.
1024
1025 chomp( my $input = <STDIN> );
1026
1027 my $regex = qr/$input/is;
1028
1029 $string =~ m/$regex/ # same as m/$input/is;
1030
1031 You might also want to trap any errors by wrapping an "eval" block
1032 around the whole thing.
1033
1034 chomp( my $input = <STDIN> );
1035
1036 eval {
1037 if( $string =~ m/\Q$input\E/ ) { ... }
1038 };
1039 warn $@ if $@;
1040
1041 Or...
1042
1043 my $regex = eval { qr/$input/is };
1044 if( defined $regex ) {
1045 $string =~ m/$regex/;
1046 }
1047 else {
1048 warn $@;
1049 }
1050
1052 Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1053 authors as noted. All rights reserved.
1054
1055 This documentation is free; you can redistribute it and/or modify it
1056 under the same terms as Perl itself.
1057
1058 Irrespective of its distribution, all code examples in this file are
1059 hereby placed into the public domain. You are permitted and encouraged
1060 to use this code in your own programs for fun or for profit as you see
1061 fit. A simple comment in the code giving credit would be courteous but
1062 is not required.
1063
1064
1065
1066perl v5.28.1 2019-01-26 perlfaq6(3)