Damian Conway > Regexp-Common-0.01 > Regexp::Common

Download:
Regexp-Common-0.01.tar.gz

Dependencies

Annotate this POD (2)

Related Modules

Parse::RecDescent
Data::Dumper
Text::Balanced
Test::More
Scalar::Util
List::Util
HTML::Parser
Params::Validate
Date::Manip
Class::DBI
more...
By perlmonks.org

CPAN RT

New  6
Open  11
View/Report Bugs
Module Version: 0.01   Source   Latest Release: Regexp-Common-2013031301

NAME ^

Regexp::Common - Provide commonly requested regular expressions

SYNOPSIS ^

 # STANDARD USAGE 

 use Regexp::Common;

 while (<>) {
        /$RE{num}{real}/                and print q{a number\n};
        /$RE{quoted}                    and print q{a ['"`] quoted string\n};
        /$RE{delimited}{-delim=>'/'}/   and print q{a /.../ sequence\n};
        /$RE{balanced}{-parens=>'()'}/  and print q{balanced parentheses\n};
        /$RE{profanity}/                and print q{a #*@%-ing word\n};
 }


 # SUBROUTINE-BASED INTERFACE

 use Regexp::Common 'RE';

 while (<>) {
        $_ =~ RE_num_real()              and print q{a number\n};
        $_ =~ RE_quoted()                and print q{a ['"`] quoted string\n};
        $_ =~ RE_delimited(-delim=>'/')  and print q{a /.../ sequence\n};
        $_ =~ RE_balanced(-parens=>'()'} and print q{balanced parentheses\n};
        $_ =~ RE_profanity()             and print q{a #*@%-ing word\n};
 }


 # IN-LINE MATCHING...

 if ( $RE{num}{int}->matches($text} ) {...}


 # ...AND SUBSTITUTION

 my $cropped = $RE{ws}{crop}->subs($uncropped);


 # ROLL-YOUR-OWN PATTERNS

 use Regexp::Common 'pattern';

 pattern name   => ['name', 'mine'],
         create => '(?i:J[.]?\s+A[.]?\s+Perl-Hacker)',
         ;

 my $name_matcher = $RE{name}{mine};

 pattern name    => [ 'lineof', '-char=_' ],
         create  => sub {
                        my $flags = shift;
                        my $char = quotemeta $flags->{-char};
                        return '(?:^$char+$)';
                    },
         matches => sub {
                        my ($self, $str) = @_;
                        return $str !~ /[^$self->{flags}{-char}]/;
                    },
         subs   => sub {
                        my ($self, $str, $replacement) = @_;
                        $_[1] =~ s/^$self->{flags}{-char}+$//g;
                   },
         ;

 my $asterisks = $RE{lineof}{-char=>'*'};

DESCRIPTION ^

By default, this module exports a single hash (%RE) that stores or generates commonly needed regular expressions (see "List of available patterns").

There is an alternative, subroutine-based syntax described in "Subroutine-based interface".

General syntax for requesting patterns

To access a particular pattern, %RE is treated as a hierarchical hash of hashes (of hashes...), with each successive key being an identifier. For example, to access the pattern that matches real numbers, you specify:

        $RE{num}{real}

and to access the pattern that matches integers:

        $RE{num}{int}

Deeper layers of the hash are used to specify flags: arguments that modify the resulting pattern in some way. The keys used to access these layers are prefixed with a minus sign and may include a value that is introduced by an equality sign. For example, to access the pattern that matches base-2 real numbers with embedded commas separating groups of three digits (e.g. 10,101,110.110101101):

        $RE{num}{real}{'-base=2'}{'-sep=,'}{'-group=3'}

Through the magic of Perl, these flag layers may be specified in any order (and even interspersed through the identifier keys!) so you could get the same pattern with:

        $RE{num}{real}{'-sep=,'}{'-group=3'}{'-base=2'}

or:

        $RE{num}{'-base=2'}{real}{'-group=3'}{'-sep=,'}

or even:

        $RE{'-base=2'}{'-group=3'}{'-sep=,'}{num}{real}

etc.

Note, however, that the relative order of amongst the identifier keys is significant. That is:

        $RE{list}{set}

would not be the same as:

        $RE{set}{list}

Alternative flag syntax

As the examples in the previous section indicate, the syntax for specifying flags is somewhat cumbersome, because of the need to quote the entire (non-identifier) key-plus-value. To make such specifications less ugly, Regexp::Common permanently changes the value of the magical $; variable (setting it to the character '='), so that flags can also be specified like so:

        $RE{num}{real}{-base=>2}{-group=>3}{-sep=>','}

This syntax is preferred, and is used throughout the rest of this document.

In the unlikely case that the non-standard value of $; breaks your program, this behaviour can be disabled by importing the module as:

        use Regexp::Common 'clean';

Universal flags

Normally, flags are specific to a single pattern. However, there is one flag that all patterns may specify.

By default, the patterns provided by %RE contain no capturing parentheses. However, if the -keep flag is specified (it requires no value) then any significant substrings that the pattern matches are captured. For example:

        if ($str =~ $RE{num}{real}{-keep}) {
                $number   = $1;
                $whole    = $3;
                $decimals = $5;
        }

Special care is needed if a "kept" pattern is interpolated into a larger regular expression, as the presence of other capturing parentheses is likely to change the "number variables" into which significant substrings are saved.

See also "Adding new regular expressions", which describes how to create new patterns with "optional" capturing brackets that respond to -keep.

OO interface and inline matching/substitution

The patterns returned from %RE are objects, so rather than writing:

        if ($str =~ /$RE{some}{pattern}/ ) {...}

you can write:

        if ( $RE{some}{pattern}->matches($str) ) {...}

For matching this would seem to have no great advantage apart from readability (but see below).

For substitutions, it has other significant benefits. Frequently you want to perform a substitution on a string without changing the original. Most people use this:

        $changed = $original;
        $changed =~ s/$RE{some}{pattern}/$replacement/;

The more adept use:

        ($changed = $original) =~ s/$RE{some}{pattern}/$replacement/;

Regexp::Common allows you do write this:

        $changed = $RE{some}{pattern}->subs($original=>$replacement);

Apart from reducing precedence-angst, this approach has the daded advantages that the substitution behaviour can be optimized fro the regular expression, and the replacement string can be provided by default (see "Adding new regular expressions").

For example, in the implementation of this substitution:

        $cropped = $RE{ws}{crop}->subs($uncropped);

the default empty string is provided automatically, and the substitution is optimized to use:

        $uncropped =~ s/^\s+//;
        $uncropped =~ s/\s+$//;

rather than:

        $uncropped =~ s/^\s+|\s+$//g;

Subroutine-based interface

The hash-based interface was chosen because it allows regexes to be effortlessly interpolated, and because it also allows them to be "curried". For example:

        my $num = $RE{num}{int};

        my $comma'd    = $num->{-sep=>','}{-group=>3};
        my $duodecimal = $num->{-base=>12};

However, the use of tied hashes does make the access to Regexp::Common patterns slower than it might otherwise be. In contexts where impatience overrules laziness, Regexp::Common provides an additional subroutine-based interface.

For each (sub-)entry in the %RE hash ($RE{key1}{key2}{etc}), there is a corresponding exportable subroutine: RE_key1_key2_etc(). The name of each subroutine is the underscore-separated concatenation of the non-flag keys that locate the same pattern in %RE. Flags are passed to the subroutine in its argument list. Thus:

        use Regexp::Common qw( RE_ws_crop RE_num_real RE_profanity );

        $str =~ RE_ws_crop() and die "Surrounded by whitespace";

        $str =~ RE_num_real(-base=>8, -sep=>" ") or next;

        $offensive = RE_profanity(-keep);
        $str =~ s/$offensive/$bad{$1}++; "<expletive deleted>"/ge;

Note that, unlike the hash-based interface (which returns objects), these subroutines return ordinary qr'd regular expressions. Hence they do not curry, nor do they provide the OO match and substitution inlining described in the previous section.

It is also possible to export subroutines for all available patterns like so:

        use Regexp::Common 'RE_ALL';

Adding new regular expressions

You can add your own regular expressions to the %RE hash at run-time, using the exportable pattern subroutine. It expects a hash-like list of key/value pairs that specify the behaviour of the pattern. The various possible argument pairs are:

name => [ @list ]

A required argument that specifies the name of the pattern, and any flags it may take, via a reference to a list of strings. For example:

         pattern name => [qw( line of -char )],
                 # other args here
                 ;

This specifies an entry $RE{line}{of}, which may take a -char flag.

Flags may also be specified with a default value, which is then used whenever the flag is omitted, or specified without an explicit value. For example:

         pattern name => [qw( line of -char=_ )],
                 # default char is '_'
                 # other args here
                 ;
create => $sub_ref_or_string

A required argument that specifies either a string that is to be returned as the pattern:

        pattern name    => [qw( line of underscores )],
                create  => q/(?:^_+$)/
                ;

or a reference to a subroutine that will be called to create the pattern:

        pattern name    => [qw( line of -char=_ )],
                create  => sub {
                                my ($self, $flags) = @_;
                                my $char = quotemeta $flags->{-char};
                                return '(?:^$char+$)';
                            },
                ;

If the subroutine version is used, the subroutine will be called with three arguments: a reference to the pattern object itself, a reference to a hash containing the flags and their values, and a reference to an array containing the non-flag keys.

Whatever the subroutine returns is stringified as the pattern.

No matter how the pattern is created, it is immediately postprocessed to include or exclude capturing parentheses (according to the value of the -keep flag). To specify such "optional" capturing parentheses within the regular expression associated with create, use the notation (?k:...). Any parentheses of this type will be converted to (...) when the -keep flag is specified, or (?:...) when it is not. It is a Regexp::Common convention that the outermost capturing parentheses always capture the entire pattern, but this is not enforced.

matches => $sub_ref

An optional argument that specifies a subroutine that is to be called when the $RE{...}->matches(...) method of this pattern is invoked.

The subroutine should expect two arguments: a reference to the pattern object itself, and the string to be matched against.

It should return the same types of values as a m/.../ does.

        pattern name    => [qw( line of -char )],
                create  => sub {...},
                matches => sub {
                                my ($self, $str) = @_;
                                return $str !~ /[^$self->{flags}{-char}]/;
                           },
                ;
subs => $sub_ref

An optional argument that specifies a subroutine that is to be called when the $RE{...}->subs(...) method of this pattern is invoked.

The subroutine should expect three arguments: a reference to the pattern object itself, the string to be changed, and the value to be substituted into it. The third argument may be undef, indicating the default substitution is required.

The subroutine should return the same types of values as an s/.../.../ does.

For example:

        pattern name    => [ 'lineof', '-char=_' ],
                create  => sub {...},
                subs   => sub {
                                my ($self, $str, $ignore_replacement) = @_;
                                $_[1] =~ s/^$self->{flags}{-char}+$//g;
                          },
                 ;

Note that such a subroutine will almost always need to modify $_[1] directly.

version => $minimum_perl_version

If this argument is given, it specifies the minimum version of perl required to use the new pattern. Attempts to use the pattern with earlier versions of perl will generate a fatal diagnostic.

List of available patterns

The following patterns are currently available:

$RE{balanced}{-parens}

Returns a pattern that matches a string that starts with the nominated opening parenthesis or bracket, contains characters and properly nested parenthesized subsequences, and ends in the matching parenthesis.

More than one type of parenthesis can be specified:

        $RE{balanced}{-parens=>'(){}'}

in which case all specified parenthesis types must be correctly balanced within the string.

Under -keep:

$1

captures the entire expression

$RE{num}{int}{-sep}{-group}

Returns a pattern that matches a decimal integer.

If -sep=P is specified, the pattern P is required as a grouping marker within the number.

If -group=N is specified, digits between grouping markers must be grouped in sequences of exactly N characters. The default value of N is 3.

For example:

        $RE{num}{int}                            # match 1234567
        $RE{num}{int}{-sep=>','}                 # match 1,234,567
        $RE{num}{int}{-sep=>',?'}                # match 1234567 or 1,234,567
        $RE{num}{int}{-sep=>'.'}{-group=>4}      # match 1.2345.6789

Under -keep:

$1

captures the entire number

$2

captures the optional sign number

$3

captures the complete set of digits

$RE{num}{real}{-base}{-radix}{-places}{-sep}{-group}{-expon}

Returns a pattern that matches a floating-point number.

If -base=N is specified, the number is assumed to be in that base (with A..Z representing the digits for 11..36). By default, the base is 10.

If -radix=P is specified, the pattern P is used as the radix point for the number (i.e. the "decimal point" in base 10). The default is qr/[.]/.

If -places=N is specified, the number is assumed to have exactly N places after the radix point. If -places=M,N is specified, the number is assumed to have between M and N places after the radix point. By default, the number of places is unrestricted.

If -sep=P specified, the pattern P is required as a grouping marker within the pre-radix section of the number. By default, no separator is allowed.

If -group=N is specified, digits between grouping separators must be grouped in sequences of exactly N characters. The default value of N is 3.

If -expon=P is specified, the pattern P is used as the exponential marker. The default value of P is qr/[Ee]/.

For example:

        $RE{num}{real}                  # matches 123.456 or -0.1234567
        $RE{num}{real}{-places=2}       # matches 123.45 or -0.12
        $RE{num}{real}{-places='0,3'}   # matches 123.456 or 0 or 9.8
        $RE{num}{real}{-sep=>'[,.]?'}   # matches 123,456 or 123.456
        $RE{num}{real}{-base=>3'}       # matches 121.102

Under -keep:

$1

captures the entire match

$2

captures the optional sign

$3

captures the complete mantissa

$4

captures the whole number portion of the mantissa

$5

captures the radix point

$6

captures the fractional portion of the mantissa

$7

captures the optional exponent marker

$8

captures the entire exponent value

$9

captures the optional sign of the exponent

$10

captures the digits of the exponent

$RE{num}{dec}{-radix}{-places}{-sep}{-group}{-expon}

A synonym for $RE{num}{real}{-base=10}{...}>

$RE{num}{oct}{-radix}{-places}{-sep}{-group}{-expon}

A synonym for $RE{num}{real}{-base=8}{...}>

$RE{num}{bin}{-radix}{-places}{-sep}{-group}{-expon}

A synonym for $RE{num}{real}{-base=2}{...}>

$RE{num}{hex}{-radix}{-places}{-sep}{-group}{-expon}

A synonym for $RE{num}{real}{-base=16}{...}>

$RE{comment}{language}

A comment string in the nominated language.

Available languages are:

        $RE{comment}{C}
        $RE{comment}{C++}
        $RE{comment}{shell}
        $RE{comment}{Perl}

Under -keep:

$1

captures the entire match

$2

captures the opening comment marker (except for $RE{comment}{C++})

$3

captures the contents of the comment (except for $RE{comment}{C++})

$4

captures the closing comment marker (except for $RE{comment}{C++})

$RE{profanity}

Returns a pattern matching words -- such as Carlin's "big seven" -- that are most likely to give offense. Note that correct anatomical terms are deliberately not included in the list.

Under -keep:

$1

captures the entire word

$RE{profanity}{contextual}

Returns a pattern matching words that are likely to give offense when used in specific contexts, but which also have genuinely non-offensive meanings.

Under -keep:

$1

captures the entire word

$RE{ws}{crop}

Returns a pattern that identifies leading or trailing whitespace.

For example:

        $str =~ s/$RE{ws}{crop}//g;     # Delete surrounding whitespace

The call:

        $RE{ws}{crop}->subs($str);

is optimized (but probably still slower than doing the s///g explicitly).

This pattern does not capture under -keep.

$RE{delimited}{-delim}{-esc}

Returns a pattern that matches a single-character-delimited substring, with optional internal escaping of the delimiter.

When -delim=S is specified, each character in the sequence S is a possible delimiter. There is no default delimiter, so this flag must always be specified.

If -esc=S is specified, each character in the sequence S is the delimiter for the corresponding character in the -delim=S list. The default escape is backslash.

For example:

        $RE{delimited}{-delim=>'"'}             # match "a \" delimited string"
        $RE{delimited}{-delim=>'"'}{-esc=>'"'}  # match "a "" delimited string"
        $RE{delimited}{-delim=>'/'}             # match /a \/ delimited string/
        $RE{delimited}{-delim=>q{'"}}           # match "string" or 'string'

Under -keep:

$1

captures the entire match

$2

captures the opening delimiter (provided only one delimiter was specified)

$3

captures delimited portion of the string (provided only one delimiter was specified)

$4

captures the closing delimiter (provided only one delimiter was specified)

$RE{quoted}{-esc}

A synonym for $RE{delimited}{q{-delim='"`}{...}}

$RE{list}{-pat}{-sep}{-lastsep}

Returns a pattern matching a list of (at least two) substrings.

If -pat=P is specified, it defines the pattern for each substring in the list. By default, P is qr/.*?/.

If -sep=P is specified, it defines the pattern P to be used as a separator between each pair of substrings in the list, except the final two. By default P is qr/\s*,\s*/.

If -lastsep=P is specified, it defines the pattern P to be used as a separator between the final two substrings in the list. By default P is the same as the pattern specified by the -sep flag.

For example:

        $RE{list}{-pat=>'\w+'}                # match a list of word chars
        $RE{list}{-pat=>$RE{num}{real}}       # match a list of numbers
        $RE{list}{-sep=>"\t"}                 # match a tab-separated list
        $RE{list}{-lastsep=>',\s+and\s+'}     # match a proper English list

Under -keep:

$1

captures the entire list

$2

captures the last separator

$RE{list}{conj}{-word=PATTERN}

An alias for $RE{list}{-lastsep='\s*,?\s*PATTERN\s*'}>

If -word is not specified, the default pattern is qr/and|or/.

For example:

        $RE{list}{conj}{-word=>'et'}             # match Jean, Paul, et Satre
        $RE{list}{conj}{-word=>'oder'}           # match Bonn, Koln oder Hamburg

$RE{list}{and}

An alias for $RE{list}{conj}{-word='and'}>

$RE{list}{or}

An alias for $RE{list}{conj}{-word='or'}>

$RE{net}{IPv4}

Returns a pattern that matches a valid IP address in "dotted decimal"

For this pattern and the next four, under -keep:

$1

captures the entire match

$2

captures the first component of the address

$3

captures the second component of the address

$4

captures the third component of the address

$5

captures the final component of the address

$RE{net}{IPv4}{dec}{-sep}

Returns a pattern that matches a valid IP address in "dotted decimal"

If -sep=P is specified the pattern P is used as the separator. By default P is qr/[.]/.

$RE{net}{IPv4}{hex}{-sep}

Returns a pattern that matches a valid IP address in "dotted hexadecimal"

If -sep=P is specified the pattern P is used as the separator. By default P is qr/[.]/. -sep=""> and -sep=" "> are useful alternatives.

$RE{net}{IPv4}{oct}{-sep}

Returns a pattern that matches a valid IP address in "dotted octal"

If -sep=P is specified the pattern P is used as the separator. By default P is qr/[.]/.

$RE{net}{IPv4}{bin}{-sep}

Returns a pattern that matches a valid IP address in "dotted binary"

If -sep=P is specified the pattern P is used as the separator. By default P is qr/[.]/.

Forthcoming patterns and features

Future releases of the module will also provide patterns for the following:

        * email addresses 
        * HTML/XML tags
        * more numerical matchers,
        * mail headers (including multiline ones),
        * URLS (various genres)
        * telephone numbers of various countries
        * currency (universal 3 letter format, Latin-1, currency names)
        * dates
        * binary formats (e.g. UUencoded, MIMEd)

If you have other patterns or pattern generators that you think would be generally useful, please send them to the author -- preferably as source code using the pattern subroutine. Submissions that include a set of tests, will be especially welcome.

DIAGNOSTICS ^

Can't export unknown subroutine %s

The subroutine-based interface didn't recognize the requested subroutine. Often caused by a spelling mistake or an incompletely specified name.

Can't create unknown regex: $RE{...}

Regexp::Common doesn't have a generator for the requested pattern. Often indicates a mispelt or missing parameter.

Perl %f does not support the pattern $RE{...}. You need Perl %f or later

The requested pattern requires advanced regex features (e.g. recursion) that not available in your version of Perl. Time to upgrade.

pattern() requires argument: name = [ @list ]>

Every user-defined pattern specification must have a name.

pattern() requires argument: create = $sub_ref_or_string>

Every user-defined pattern specification must provide a pattern creation mechanism: either a pattern string or a reference to a subroutine that returns the pattern string.

Base must be between 1 and 36

The $RE{num}{real}{-base='N'}> pattern uses the characters [0-9A-Z] to represent the digits of various bases. Hence it only produces regular expressions for bases up to hexatricensimal.

Must specify delimiter in $RE{delimited}

The pattern has no default delimiter. You need to write: $RE{delimited}{-delim=X'}> for some character X

ACKNOWLEDGEMENTS ^

Deepest thanks to the many people who have encouraged and contributed to this project, especially: Elijah, Jarkko, Tom, Nat, Ed, and Vivek.

AUTHOR ^

Damian Conway (damian@conway.org)

BUGS AND IRRITATIONS ^

Bound to be plenty.

For a start, there are many common regexes missing. Send them in!

COPYRIGHT ^

         Copyright (c) 2001, Damian Conway. All Rights Reserved.
       This module is free software. It may be used, redistributed
      and/or modified under the terms of the Perl Artistic License
            (see http://www.perl.com/perl/misc/Artistic.html)
syntax highlighting: