1N/A=head1 NAME
1N/A
1N/Aperlfaq6 - Regular Expressions ($Revision: 1.20 $, $Date: 2003/01/03 20:05:28 $)
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThis section is surprisingly small because the rest of the FAQ is
1N/Alittered with answers involving regular expressions. For example,
1N/Adecoding a URL and checking whether something is a number are handled
1N/Awith regular expressions, but those answers are found elsewhere in
1N/Athis document (in L<perlfaq9>: ``How do I decode or create those %-encodings
1N/Aon the web'' and L<perlfaq4>: ``How do I determine whether a scalar is
1N/Aa number/whole/integer/float'', to be precise).
1N/A
1N/A=head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
1N/A
1N/AThree techniques can make regular expressions maintainable and
1N/Aunderstandable.
1N/A
1N/A=over 4
1N/A
1N/A=item Comments Outside the Regex
1N/A
1N/ADescribe what you're doing and how you're doing it, using normal Perl
1N/Acomments.
1N/A
1N/A # turn the line into the first word, a colon, and the
1N/A # number of characters on the rest of the line
1N/A s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
1N/A
1N/A=item Comments Inside the Regex
1N/A
1N/AThe C</x> modifier causes whitespace to be ignored in a regex pattern
1N/A(except in a character class), and also allows you to use normal
1N/Acomments there, too. As you can imagine, whitespace and comments help
1N/Aa lot.
1N/A
1N/AC</x> lets you turn this:
1N/A
1N/A s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
1N/A
1N/Ainto this:
1N/A
1N/A s{ < # opening angle bracket
1N/A (?: # Non-backreffing grouping paren
1N/A [^>'"] * # 0 or more things that are neither > nor ' nor "
1N/A | # or else
1N/A ".*?" # a section between double quotes (stingy match)
1N/A | # or else
1N/A '.*?' # a section between single quotes (stingy match)
1N/A ) + # all occurring one or more times
1N/A > # closing angle bracket
1N/A }{}gsx; # replace with nothing, i.e. delete
1N/A
1N/AIt's still not quite so clear as prose, but it is very useful for
1N/Adescribing the meaning of each part of the pattern.
1N/A
1N/A=item Different Delimiters
1N/A
1N/AWhile we normally think of patterns as being delimited with C</>
1N/Acharacters, they can be delimited by almost any character. L<perlre>
1N/Adescribes this. For example, the C<s///> above uses braces as
1N/Adelimiters. Selecting another delimiter can avoid quoting the
1N/Adelimiter within the pattern:
1N/A
1N/A s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
1N/A s#/usr/local#/usr/share#g; # better
1N/A
1N/A=back
1N/A
1N/A=head2 I'm having trouble matching over more than one line. What's wrong?
1N/A
1N/AEither you don't have more than one line in the string you're looking
1N/Aat (probably), or else you aren't using the correct modifier(s) on
1N/Ayour pattern (possibly).
1N/A
1N/AThere are many ways to get multiline data into a string. If you want
1N/Ait to happen automatically while reading input, you'll want to set $/
1N/A(probably to '' for paragraphs or C<undef> for the whole file) to
1N/Aallow you to read more than one line at a time.
1N/A
1N/ARead L<perlre> to help you decide which of C</s> and C</m> (or both)
1N/Ayou might want to use: C</s> allows dot to include newline, and C</m>
1N/Aallows caret and dollar to match next to a newline, not just at the
1N/Aend of the string. You do need to make sure that you've actually
1N/Agot a multiline string in there.
1N/A
1N/AFor example, this program detects duplicate words, even when they span
1N/Aline breaks (but not paragraph ones). For this example, we don't need
1N/AC</s> because we aren't using dot in a regular expression that we want
1N/Ato cross line boundaries. Neither do we need C</m> because we aren't
1N/Awanting caret or dollar to match at any point inside the record next
1N/Ato newlines. But it's imperative that $/ be set to something other
1N/Athan the default, or else we won't actually ever have a multiline
1N/Arecord read in.
1N/A
1N/A $/ = ''; # read in more whole paragraph, not just one line
1N/A while ( <> ) {
1N/A while ( /\b([\w'-]+)(\s+\1)+\b/gi ) { # word starts alpha
1N/A print "Duplicate $1 at paragraph $.\n";
1N/A }
1N/A }
1N/A
1N/AHere's code that finds sentences that begin with "From " (which would
1N/Abe mangled by many mailers):
1N/A
1N/A $/ = ''; # read in more whole paragraph, not just one line
1N/A while ( <> ) {
1N/A while ( /^From /gm ) { # /m makes ^ match next to \n
1N/A print "leading from in paragraph $.\n";
1N/A }
1N/A }
1N/A
1N/AHere's code that finds everything between START and END in a paragraph:
1N/A
1N/A undef $/; # read in whole file, not just one line or paragraph
1N/A while ( <> ) {
1N/A while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
1N/A print "$1\n";
1N/A }
1N/A }
1N/A
1N/A=head2 How can I pull out lines between two patterns that are themselves on different lines?
1N/A
1N/AYou can use Perl's somewhat exotic C<..> operator (documented in
1N/AL<perlop>):
1N/A
1N/A perl -ne 'print if /START/ .. /END/' file1 file2 ...
1N/A
1N/AIf you wanted text and not lines, you would use
1N/A
1N/A perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
1N/A
1N/ABut if you want nested occurrences of C<START> through C<END>, you'll
1N/Arun up against the problem described in the question in this section
1N/Aon matching balanced text.
1N/A
1N/AHere's another example of using C<..>:
1N/A
1N/A while (<>) {
1N/A $in_header = 1 .. /^$/;
1N/A $in_body = /^$/ .. eof();
1N/A # now choose between them
1N/A } continue {
1N/A reset if eof(); # fix $.
1N/A }
1N/A
1N/A=head2 I put a regular expression into $/ but it didn't work. What's wrong?
1N/A
1N/AUp to Perl 5.8.0, $/ has to be a string. This may change in 5.10,
1N/Abut don't get your hopes up. Until then, you can use these examples
1N/Aif you really need to do this.
1N/A
1N/AUse the four argument form of sysread to continually add to
1N/Aa buffer. After you add to the buffer, you check if you have a
1N/Acomplete line (using your regular expression).
1N/A
1N/A local $_ = "";
1N/A while( sysread FH, $_, 8192, length ) {
1N/A while( s/^((?s).*?)your_pattern/ ) {
1N/A my $record = $1;
1N/A # do stuff here.
1N/A }
1N/A }
1N/A
1N/A You can do the same thing with foreach and a match using the
1N/A c flag and the \G anchor, if you do not mind your entire file
1N/A being in memory at the end.
1N/A
1N/A local $_ = "";
1N/A while( sysread FH, $_, 8192, length ) {
1N/A foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
1N/A # do stuff here.
1N/A }
1N/A substr( $_, 0, pos ) = "" if pos;
1N/A }
1N/A
1N/A
1N/A=head2 How do I substitute case insensitively on the LHS while preserving case on the RHS?
1N/A
1N/AHere's a lovely Perlish solution by Larry Rosler. It exploits
1N/Aproperties of bitwise xor on ASCII strings.
1N/A
1N/A $_= "this is a TEsT case";
1N/A
1N/A $old = 'test';
1N/A $new = 'success';
1N/A
1N/A s{(\Q$old\E)}
1N/A { uc $new | (uc $1 ^ $1) .
1N/A (uc(substr $1, -1) ^ substr $1, -1) x
1N/A (length($new) - length $1)
1N/A }egi;
1N/A
1N/A print;
1N/A
1N/AAnd here it is as a subroutine, modeled after the above:
1N/A
1N/A sub preserve_case($$) {
1N/A my ($old, $new) = @_;
1N/A my $mask = uc $old ^ $old;
1N/A
1N/A uc $new | $mask .
1N/A substr($mask, -1) x (length($new) - length($old))
1N/A }
1N/A
1N/A $a = "this is a TEsT case";
1N/A $a =~ s/(test)/preserve_case($1, "success")/egi;
1N/A print "$a\n";
1N/A
1N/AThis prints:
1N/A
1N/A this is a SUcCESS case
1N/A
1N/AAs an alternative, to keep the case of the replacement word if it is
1N/Alonger than the original, you can use this code, by Jeff Pinyan:
1N/A
1N/A sub preserve_case {
1N/A my ($from, $to) = @_;
1N/A my ($lf, $lt) = map length, @_;
1N/A
1N/A if ($lt < $lf) { $from = substr $from, 0, $lt }
1N/A else { $from .= substr $to, $lf }
1N/A
1N/A return uc $to | ($from ^ uc $from);
1N/A }
1N/A
1N/AThis changes the sentence to "this is a SUcCess case."
1N/A
1N/AJust to show that C programmers can write C in any programming language,
1N/Aif you prefer a more C-like solution, the following script makes the
1N/Asubstitution have the same case, letter by letter, as the original.
1N/A(It also happens to run about 240% slower than the Perlish solution runs.)
1N/AIf the substitution has more characters than the string being substituted,
1N/Athe case of the last character is used for the rest of the substitution.
1N/A
1N/A # Original by Nathan Torkington, massaged by Jeffrey Friedl
1N/A #
1N/A sub preserve_case($$)
1N/A {
1N/A my ($old, $new) = @_;
1N/A my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
1N/A my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
1N/A my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
1N/A
1N/A for ($i = 0; $i < $len; $i++) {
1N/A if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
1N/A $state = 0;
1N/A } elsif (lc $c eq $c) {
1N/A substr($new, $i, 1) = lc(substr($new, $i, 1));
1N/A $state = 1;
1N/A } else {
1N/A substr($new, $i, 1) = uc(substr($new, $i, 1));
1N/A $state = 2;
1N/A }
1N/A }
1N/A # finish up with any remaining new (for when new is longer than old)
1N/A if ($newlen > $oldlen) {
1N/A if ($state == 1) {
1N/A substr($new, $oldlen) = lc(substr($new, $oldlen));
1N/A } elsif ($state == 2) {
1N/A substr($new, $oldlen) = uc(substr($new, $oldlen));
1N/A }
1N/A }
1N/A return $new;
1N/A }
1N/A
1N/A=head2 How can I make C<\w> match national character sets?
1N/A
1N/APut C<use locale;> in your script. The \w character class is taken
1N/Afrom the current locale.
1N/A
1N/ASee L<perllocale> for details.
1N/A
1N/A=head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
1N/A
1N/AYou can use the POSIX character class syntax C</[[:alpha:]]/>
1N/Adocumented in L<perlre>.
1N/A
1N/ANo matter which locale you are in, the alphabetic characters are
1N/Athe characters in \w without the digits and the underscore.
1N/AAs a regex, that looks like C</[^\W\d_]/>. Its complement,
1N/Athe non-alphabetics, is then everything in \W along with
1N/Athe digits and the underscore, or C</[\W\d_]/>.
1N/A
1N/A=head2 How can I quote a variable to use in a regex?
1N/A
1N/AThe Perl parser will expand $variable and @variable references in
1N/Aregular expressions unless the delimiter is a single quote. Remember,
1N/Atoo, that the right-hand side of a C<s///> substitution is considered
1N/Aa double-quoted string (see L<perlop> for more details). Remember
1N/Aalso that any regex special characters will be acted on unless you
1N/Aprecede the substitution with \Q. Here's an example:
1N/A
1N/A $string = "Placido P. Octopus";
1N/A $regex = "P.";
1N/A
1N/A $string =~ s/$regex/Polyp/;
1N/A # $string is now "Polypacido P. Octopus"
1N/A
1N/ABecause C<.> is special in regular expressions, and can match any
1N/Asingle character, the regex C<P.> here has matched the <Pl> in the
1N/Aoriginal string.
1N/A
1N/ATo escape the special meaning of C<.>, we use C<\Q>:
1N/A
1N/A $string = "Placido P. Octopus";
1N/A $regex = "P.";
1N/A
1N/A $string =~ s/\Q$regex/Polyp/;
1N/A # $string is now "Placido Polyp Octopus"
1N/A
1N/AThe use of C<\Q> causes the <.> in the regex to be treated as a
1N/Aregular character, so that C<P.> matches a C<P> followed by a dot.
1N/A
1N/A=head2 What is C</o> really for?
1N/A
1N/AUsing a variable in a regular expression match forces a re-evaluation
1N/A(and perhaps recompilation) each time the regular expression is
1N/Aencountered. The C</o> modifier locks in the regex the first time
1N/Ait's used. This always happens in a constant regular expression, and
1N/Ain fact, the pattern was compiled into the internal format at the same
1N/Atime your entire program was.
1N/A
1N/AUse of C</o> is irrelevant unless variable interpolation is used in
1N/Athe pattern, and if so, the regex engine will neither know nor care
1N/Awhether the variables change after the pattern is evaluated the I<very
1N/Afirst> time.
1N/A
1N/AC</o> is often used to gain an extra measure of efficiency by not
1N/Aperforming subsequent evaluations when you know it won't matter
1N/A(because you know the variables won't change), or more rarely, when
1N/Ayou don't want the regex to notice if they do.
1N/A
1N/AFor example, here's a "paragrep" program:
1N/A
1N/A $/ = ''; # paragraph mode
1N/A $pat = shift;
1N/A while (<>) {
1N/A print if /$pat/o;
1N/A }
1N/A
1N/A=head2 How do I use a regular expression to strip C style comments from a file?
1N/A
1N/AWhile this actually can be done, it's much harder than you'd think.
1N/AFor example, this one-liner
1N/A
1N/A perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
1N/A
1N/Awill work in many but not all cases. You see, it's too simple-minded for
1N/Acertain kinds of C programs, in particular, those with what appear to be
1N/Acomments in quoted strings. For that, you'd need something like this,
1N/Acreated by Jeffrey Friedl and later modified by Fred Curtis.
1N/A
1N/A $/ = undef;
1N/A $_ = <>;
1N/A s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs
1N/A print;
1N/A
1N/AThis could, of course, be more legibly written with the C</x> modifier, adding
1N/Awhitespace and comments. Here it is expanded, courtesy of Fred Curtis.
1N/A
1N/A s{
1N/A /\* ## Start of /* ... */ comment
1N/A [^*]*\*+ ## Non-* followed by 1-or-more *'s
1N/A (
1N/A [^/*][^*]*\*+
1N/A )* ## 0-or-more things which don't start with /
1N/A ## but do end with '*'
1N/A / ## End of /* ... */ comment
1N/A
1N/A | ## OR various things which aren't comments:
1N/A
1N/A (
1N/A " ## Start of " ... " string
1N/A (
1N/A \\. ## Escaped char
1N/A | ## OR
1N/A [^"\\] ## Non "\
1N/A )*
1N/A " ## End of " ... " string
1N/A
1N/A | ## OR
1N/A
1N/A ' ## Start of ' ... ' string
1N/A (
1N/A \\. ## Escaped char
1N/A | ## OR
1N/A [^'\\] ## Non '\
1N/A )*
1N/A ' ## End of ' ... ' string
1N/A
1N/A | ## OR
1N/A
1N/A . ## Anything other char
1N/A [^/"'\\]* ## Chars which doesn't start a comment, string or escape
1N/A )
1N/A }{$2}gxs;
1N/A
1N/AA slight modification also removes C++ comments:
1N/A
1N/A s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs;
1N/A
1N/A=head2 Can I use Perl regular expressions to match balanced text?
1N/A
1N/AHistorically, Perl regular expressions were not capable of matching
1N/Abalanced text. As of more recent versions of perl including 5.6.1
1N/Aexperimental features have been added that make it possible to do this.
1N/ALook at the documentation for the (??{ }) construct in recent perlre manual
1N/Apages to see an example of matching balanced parentheses. Be sure to take
1N/Aspecial notice of the warnings present in the manual before making use
1N/Aof this feature.
1N/A
1N/ACPAN contains many modules that can be useful for matching text
1N/Adepending on the context. Damian Conway provides some useful
1N/Apatterns in Regexp::Common. The module Text::Balanced provides a
1N/Ageneral solution to this problem.
1N/A
1N/AOne of the common applications of balanced text matching is working
1N/Awith XML and HTML. There are many modules available that support
1N/Athese needs. Two examples are HTML::Parser and XML::Parser. There
1N/Aare many others.
1N/A
1N/AAn elaborate subroutine (for 7-bit ASCII only) to pull out balanced
1N/Aand possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,
1N/Aor C<(> and C<)> can be found in
1N/Ahttp://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz .
1N/A
1N/AThe C::Scan module from CPAN also contains such subs for internal use,
1N/Abut they are undocumented.
1N/A
1N/A=head2 What does it mean that regexes are greedy? How can I get around it?
1N/A
1N/AMost people mean that greedy regexes match as much as they can.
1N/ATechnically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
1N/AC<{}>) that are greedy rather than the whole pattern; Perl prefers local
1N/Agreed and immediate gratification to overall greed. To get non-greedy
1N/Aversions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
1N/A
1N/AAn example:
1N/A
1N/A $s1 = $s2 = "I am very very cold";
1N/A $s1 =~ s/ve.*y //; # I am cold
1N/A $s2 =~ s/ve.*?y //; # I am very cold
1N/A
1N/ANotice how the second substitution stopped matching as soon as it
1N/Aencountered "y ". The C<*?> quantifier effectively tells the regular
1N/Aexpression engine to find a match as quickly as possible and pass
1N/Acontrol on to whatever is next in line, like you would if you were
1N/Aplaying hot potato.
1N/A
1N/A=head2 How do I process each word on each line?
1N/A
1N/AUse the split function:
1N/A
1N/A while (<>) {
1N/A foreach $word ( split ) {
1N/A # do something with $word here
1N/A }
1N/A }
1N/A
1N/ANote that this isn't really a word in the English sense; it's just
1N/Achunks of consecutive non-whitespace characters.
1N/A
1N/ATo work with only alphanumeric sequences (including underscores), you
1N/Amight consider
1N/A
1N/A while (<>) {
1N/A foreach $word (m/(\w+)/g) {
1N/A # do something with $word here
1N/A }
1N/A }
1N/A
1N/A=head2 How can I print out a word-frequency or line-frequency summary?
1N/A
1N/ATo do this, you have to parse out each word in the input stream. We'll
1N/Apretend that by word you mean chunk of alphabetics, hyphens, or
1N/Aapostrophes, rather than the non-whitespace chunk idea of a word given
1N/Ain the previous question:
1N/A
1N/A while (<>) {
1N/A while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
1N/A $seen{$1}++;
1N/A }
1N/A }
1N/A while ( ($word, $count) = each %seen ) {
1N/A print "$count $word\n";
1N/A }
1N/A
1N/AIf you wanted to do the same thing for lines, you wouldn't need a
1N/Aregular expression:
1N/A
1N/A while (<>) {
1N/A $seen{$_}++;
1N/A }
1N/A while ( ($line, $count) = each %seen ) {
1N/A print "$count $line";
1N/A }
1N/A
1N/AIf you want these output in a sorted order, see L<perlfaq4>: ``How do I
1N/Asort a hash (optionally by value instead of key)?''.
1N/A
1N/A=head2 How can I do approximate matching?
1N/A
1N/ASee the module String::Approx available from CPAN.
1N/A
1N/A=head2 How do I efficiently match many regular expressions at once?
1N/A
1N/AThe following is extremely inefficient:
1N/A
1N/A # slow but obvious way
1N/A @popstates = qw(CO ON MI WI MN);
1N/A while (defined($line = <>)) {
1N/A for $state (@popstates) {
1N/A if ($line =~ /\b$state\b/i) {
1N/A print $line;
1N/A last;
1N/A }
1N/A }
1N/A }
1N/A
1N/AThat's because Perl has to recompile all those patterns for each of
1N/Athe lines of the file. As of the 5.005 release, there's a much better
1N/Aapproach, one which makes use of the new C<qr//> operator:
1N/A
1N/A # use spiffy new qr// operator, with /i flag even
1N/A use 5.005;
1N/A @popstates = qw(CO ON MI WI MN);
1N/A @poppats = map { qr/\b$_\b/i } @popstates;
1N/A while (defined($line = <>)) {
1N/A for $patobj (@poppats) {
1N/A print $line if $line =~ /$patobj/;
1N/A }
1N/A }
1N/A
1N/A=head2 Why don't word-boundary searches with C<\b> work for me?
1N/A
1N/ATwo common misconceptions are that C<\b> is a synonym for C<\s+> and
1N/Athat it's the edge between whitespace characters and non-whitespace
1N/Acharacters. Neither is correct. C<\b> is the place between a C<\w>
1N/Acharacter and a C<\W> character (that is, C<\b> is the edge of a
1N/A"word"). It's a zero-width assertion, just like C<^>, C<$>, and all
1N/Athe other anchors, so it doesn't consume any characters. L<perlre>
1N/Adescribes the behavior of all the regex metacharacters.
1N/A
1N/AHere are examples of the incorrect application of C<\b>, with fixes:
1N/A
1N/A "two words" =~ /(\w+)\b(\w+)/; # WRONG
1N/A "two words" =~ /(\w+)\s+(\w+)/; # right
1N/A
1N/A " =matchless= text" =~ /\b=(\w+)=\b/; # WRONG
1N/A " =matchless= text" =~ /=(\w+)=/; # right
1N/A
1N/AAlthough they may not do what you thought they did, C<\b> and C<\B>
1N/Acan still be quite useful. For an example of the correct use of
1N/AC<\b>, see the example of matching duplicate words over multiple
1N/Alines.
1N/A
1N/AAn example of using C<\B> is the pattern C<\Bis\B>. This will find
1N/Aoccurrences of "is" on the insides of words only, as in "thistle", but
1N/Anot "this" or "island".
1N/A
1N/A=head2 Why does using $&, $`, or $' slow my program down?
1N/A
1N/AOnce Perl sees that you need one of these variables anywhere in
1N/Athe program, it provides them on each and every pattern match.
1N/AThe same mechanism that handles these provides for the use of $1, $2,
1N/Aetc., so you pay the same price for each regex that contains capturing
1N/Aparentheses. If you never use $&, etc., in your script, then regexes
1N/AI<without> capturing parentheses won't be penalized. So avoid $&, $',
1N/Aand $` if you can, but if you can't, once you've used them at all, use
1N/Athem at will because you've already paid the price. Remember that some
1N/Aalgorithms really appreciate them. As of the 5.005 release. the $&
1N/Avariable is no longer "expensive" the way the other two are.
1N/A
1N/A=head2 What good is C<\G> in a regular expression?
1N/A
1N/AYou use the C<\G> anchor to start the next match on the same
1N/Astring where the last match left off. The regular
1N/Aexpression engine cannot skip over any characters to find
1N/Athe next match with this anchor, so C<\G> is similar to the
1N/Abeginning of string anchor, C<^>. The C<\G> anchor is typically
1N/Aused with the C<g> flag. It uses the value of pos()
1N/Aas the position to start the next match. As the match
1N/Aoperator makes successive matches, it updates pos() with the
1N/Aposition of the next character past the last match (or the
1N/Afirst character of the next match, depending on how you like
1N/Ato look at it). Each string has its own pos() value.
1N/A
1N/ASuppose you want to match all of consective pairs of digits
1N/Ain a string like "1122a44" and stop matching when you
1N/Aencounter non-digits. You want to match C<11> and C<22> but
1N/Athe letter <a> shows up between C<22> and C<44> and you want
1N/Ato stop at C<a>. Simply matching pairs of digits skips over
1N/Athe C<a> and still matches C<44>.
1N/A
1N/A $_ = "1122a44";
1N/A my @pairs = m/(\d\d)/g; # qw( 11 22 44 )
1N/A
1N/AIf you use the \G anchor, you force the match after C<22> to
1N/Astart with the C<a>. The regular expression cannot match
1N/Athere since it does not find a digit, so the next match
1N/Afails and the match operator returns the pairs it already
1N/Afound.
1N/A
1N/A $_ = "1122a44";
1N/A my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
1N/A
1N/AYou can also use the C<\G> anchor in scalar context. You
1N/Astill need the C<g> flag.
1N/A
1N/A $_ = "1122a44";
1N/A while( m/\G(\d\d)/g )
1N/A {
1N/A print "Found $1\n";
1N/A }
1N/A
1N/AAfter the match fails at the letter C<a>, perl resets pos()
1N/Aand the next match on the same string starts at the beginning.
1N/A
1N/A $_ = "1122a44";
1N/A while( m/\G(\d\d)/g )
1N/A {
1N/A print "Found $1\n";
1N/A }
1N/A
1N/A print "Found $1 after while" if m/(\d\d)/g; # finds "11"
1N/A
1N/AYou can disable pos() resets on fail with the C<c> flag.
1N/ASubsequent matches start where the last successful match
1N/Aended (the value of pos()) even if a match on the same
1N/Astring as failed in the meantime. In this case, the match
1N/Aafter the while() loop starts at the C<a> (where the last
1N/Amatch stopped), and since it does not use any anchor it can
1N/Askip over the C<a> to find "44".
1N/A
1N/A $_ = "1122a44";
1N/A while( m/\G(\d\d)/gc )
1N/A {
1N/A print "Found $1\n";
1N/A }
1N/A
1N/A print "Found $1 after while" if m/(\d\d)/g; # finds "44"
1N/A
1N/ATypically you use the C<\G> anchor with the C<c> flag
1N/Awhen you want to try a different match if one fails,
1N/Asuch as in a tokenizer. Jeffrey Friedl offers this example
1N/Awhich works in 5.004 or later.
1N/A
1N/A while (<>) {
1N/A chomp;
1N/A PARSER: {
1N/A m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; };
1N/A m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; };
1N/A m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; };
1N/A m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; };
1N/A }
1N/A }
1N/A
1N/AFor each line, the PARSER loop first tries to match a series
1N/Aof digits followed by a word boundary. This match has to
1N/Astart at the place the last match left off (or the beginning
1N/Aof the string on the first match). Since C<m/ \G( \d+\b
1N/A)/gcx> uses the C<c> flag, if the string does not match that
1N/Aregular expression, perl does not reset pos() and the next
1N/Amatch starts at the same position to try a different
1N/Apattern.
1N/A
1N/A=head2 Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
1N/A
1N/AWhile it's true that Perl's regular expressions resemble the DFAs
1N/A(deterministic finite automata) of the egrep(1) program, they are in
1N/Afact implemented as NFAs (non-deterministic finite automata) to allow
1N/Abacktracking and backreferencing. And they aren't POSIX-style either,
1N/Abecause those guarantee worst-case behavior for all cases. (It seems
1N/Athat some people prefer guarantees of consistency, even when what's
1N/Aguaranteed is slowness.) See the book "Mastering Regular Expressions"
1N/A(from O'Reilly) by Jeffrey Friedl for all the details you could ever
1N/Ahope to know on these matters (a full citation appears in
1N/AL<perlfaq2>).
1N/A
1N/A=head2 What's wrong with using grep in a void context?
1N/A
1N/AThe problem is that grep builds a return list, regardless of the context.
1N/AThis means you're making Perl go to the trouble of building a list that
1N/Ayou then just throw away. If the list is large, you waste both time and space.
1N/AIf your intent is to iterate over the list, then use a for loop for this
1N/Apurpose.
1N/A
1N/AIn perls older than 5.8.1, map suffers from this problem as well.
1N/ABut since 5.8.1, this has been fixed, and map is context aware - in void
1N/Acontext, no lists are constructed.
1N/A
1N/A=head2 How can I match strings with multibyte characters?
1N/A
1N/AStarting from Perl 5.6 Perl has had some level of multibyte character
1N/Asupport. Perl 5.8 or later is recommended. Supported multibyte
1N/Acharacter repertoires include Unicode, and legacy encodings
1N/Athrough the Encode module. See L<perluniintro>, L<perlunicode>,
1N/Aand L<Encode>.
1N/A
1N/AIf you are stuck with older Perls, you can do Unicode with the
1N/AC<Unicode::String> module, and character conversions using the
1N/AC<Unicode::Map8> and C<Unicode::Map> modules. If you are using
1N/AJapanese encodings, you might try using the jperl 5.005_03.
1N/A
1N/AFinally, the following set of approaches was offered by Jeffrey
1N/AFriedl, whose article in issue #5 of The Perl Journal talks about
1N/Athis very matter.
1N/A
1N/ALet's suppose you have some weird Martian encoding where pairs of
1N/AASCII uppercase letters encode single Martian letters (i.e. the two
1N/Abytes "CV" make a single Martian letter, as do the two bytes "SG",
1N/A"VS", "XX", etc.). Other bytes represent single characters, just like
1N/AASCII.
1N/A
1N/ASo, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
1N/Anine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
1N/A
1N/ANow, say you want to search for the single character C</GX/>. Perl
1N/Adoesn't know about Martian, so it'll find the two bytes "GX" in the "I
1N/Aam CVSGXX!" string, even though that character isn't there: it just
1N/Alooks like it is because "SG" is next to "XX", but there's no real
1N/A"GX". This is a big problem.
1N/A
1N/AHere are a few ways, all painful, to deal with it:
1N/A
1N/A $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian''
1N/A # bytes are no longer adjacent.
1N/A print "found GX!\n" if $martian =~ /GX/;
1N/A
1N/AOr like this:
1N/A
1N/A @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
1N/A # above is conceptually similar to: @chars = $text =~ m/(.)/g;
1N/A #
1N/A foreach $char (@chars) {
1N/A print "found GX!\n", last if $char eq 'GX';
1N/A }
1N/A
1N/AOr like this:
1N/A
1N/A while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
1N/A print "found GX!\n", last if $1 eq 'GX';
1N/A }
1N/A
1N/AHere's another, slightly less painful, way to do it from Benjamin
1N/AGoldberg:
1N/A
1N/A $martian =~ m/
1N/A (?!<[A-Z])
1N/A (?:[A-Z][A-Z])*?
1N/A GX
1N/A /x;
1N/A
1N/AThis succeeds if the "martian" character GX is in the string, and fails
1N/Aotherwise. If you don't like using (?!<), you can replace (?!<[A-Z])
1N/Awith (?:^|[^A-Z]).
1N/A
1N/AIt does have the drawback of putting the wrong thing in $-[0] and $+[0],
1N/Abut this usually can be worked around.
1N/A
1N/A=head2 How do I match a pattern that is supplied by the user?
1N/A
1N/AWell, if it's really a pattern, then just use
1N/A
1N/A chomp($pattern = <STDIN>);
1N/A if ($line =~ /$pattern/) { }
1N/A
1N/AAlternatively, since you have no guarantee that your user entered
1N/Aa valid regular expression, trap the exception this way:
1N/A
1N/A if (eval { $line =~ /$pattern/ }) { }
1N/A
1N/AIf all you really want to search for a string, not a pattern,
1N/Athen you should either use the index() function, which is made for
1N/Astring searching, or if you can't be disabused of using a pattern
1N/Amatch on a non-pattern, then be sure to use C<\Q>...C<\E>, documented
1N/Ain L<perlre>.
1N/A
1N/A $pattern = <STDIN>;
1N/A
1N/A open (FILE, $input) or die "Couldn't open input $input: $!; aborting";
1N/A while (<FILE>) {
1N/A print if /\Q$pattern\E/;
1N/A }
1N/A close FILE;
1N/A
1N/A=head1 AUTHOR AND COPYRIGHT
1N/A
1N/ACopyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
1N/AAll rights reserved.
1N/A
1N/AThis documentation is free; you can redistribute it and/or modify it
1N/Aunder the same terms as Perl itself.
1N/A
1N/AIrrespective of its distribution, all code examples in this file
1N/Aare hereby placed into the public domain. You are permitted and
1N/Aencouraged to use this code in your own programs for fun
1N/Aor for profit as you see fit. A simple comment in the code giving
1N/Acredit would be courteous but is not required.