perldoc > Regexp::Common

๐Ÿงฐ NAME

Regexp::Common โ€” Provide commonly requested regular expressions

๐Ÿš€ Quick Reference

Use CaseCommandDescription
Match a real number$RE{num}{real}Matches integers and floating-point numbers
Match a quoted string$RE{quoted}Matches single (''), double (""), or backtick (``) quoted strings
Match a delimited string$RE{delimited}{-delim=>'/'}Matches a string delimited by a specific character (e.g., /)
Match balanced parentheses$RE{balanced}{-parens=>'()'}Matches balanced parentheses or other paired delimiters
OO substitution (crop whitespace)$RE{ws}{crop}->subs($str)In-place removal of leading/trailing whitespace
Capture substrings$RE{num}{real}{-keep}Captures matched substrings into $1, $2, etc.
Caseโ€‘insensitive matching$RE{num}{real}{-i}Make pattern caseโ€‘insensitive
Create custom patternpattern name => ['name','mine'], create => '...'Define your own reusable regex pattern at runtime
Subroutineโ€‘based interfaceRE_num_real(-base=>8)Use exportable subroutines instead of %RE hash

๐Ÿ“‹ SYNOPSIS

 # STANDARD USAGE

 use Regexp::Common;

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


 # SUBROUTINE-BASED INTERFACE

 use Regexp::Common 'RE_ALL';

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


 # 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+$)';
                    },
         match   => 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=>'*'};

 # DECIDING WHICH PATTERNS TO LOAD.

 use Regexp::Common qw /comment number/;  # Comment and number patterns.
 use Regexp::Common qw /no_defaults/;     # Don't load any patterns.
 use Regexp::Common qw /!delimited/;      # All, but delimited patterns.

๐Ÿ“ 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 have a value; if a value is given, it's done by using a multidimensional key. 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}

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}

๐Ÿšฉ Flag syntax

In versions prior to 2.113, flags could also be written as {"-flag=value"}. This no longer works, although {"-flag$;value"} still does. However, {-flag => 'value'} is the preferred syntax.

๐ŸŒ Universal flags

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

๐Ÿ› ๏ธ 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 added advantages that the substitution behaviour can be optimized from 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 $commad     = $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';

Or you can export all subroutines with a common prefix of keys like so:

use Regexp::Common 'RE_num_ALL';

which will export RE_num_int and RE_num_real (and if you have create more patterns who have first key num, those will be exported as well). In general, RE_key1_..._keyn_ALL will export all subroutines whose pattern names have first keys key1 โ€ฆ keyn.

โž• 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:

๐Ÿ“ฆ Loading specific sets of patterns

By default, all the sets of patterns listed below are made available. However, it is possible to indicate which sets of patterns should be made available โ€” the wanted sets should be given as arguments to use. Alternatively, it is also possible to indicate which sets of patterns should not be made available โ€” those sets will be given as argument to the use statement, but are preceded with an exclaimation mark. The argument no_defaults indicates none of the default patterns should be made available. This is useful for instance if all you want is the pattern() subroutine.

Examples:

use Regexp::Common qw /comment number/;  # Comment and number patterns.
use Regexp::Common qw /no_defaults/;     # Don't load any patterns.
use Regexp::Common qw /!delimited/;      # All, but delimited patterns.

It's also possible to load your own set of patterns. If you have a module Regexp::Common::my_patterns that makes patterns available, you can have it made available with

use Regexp::Common qw /my_patterns/;

Note that the default patterns will still be made available โ€” only if you use no_defaults, or mention one of the default sets explicitly, the non mentioned defaults aren't made available.

๐Ÿ“‹ List of available patterns

The patterns listed below are currently available. Each set of patterns has its own manual page describing the details. For each pattern set named name, the manual page Regexp::Common::name describes the details.

Currently available are:

๐Ÿ”ฎ Forthcoming patterns and features

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

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

๐Ÿฉบ DIAGNOSTICS

๐Ÿ™ ACKNOWLEDGEMENTS

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

Further thanks go to: Alexandr Ciornii, Blair Zajac, Bob Stockdale, Charles Thomas, Chris Vertonghen, the CPAN Testers, David Hand, Fany, Geoffrey Leach, Hermann-Marcus Behrens, Jerome Quelin, Jim Cromie, Lars Wilke, Linda Julien, Mike Arms, Mike Castle, Mikko, Murat Uenalan, Rafa?l Garcia-Suarez, Ron Savage, Sam Vilain, Slaven Rezic, Smylers, Tim Maher, and all the others I've forgotten.

โœ๏ธ AUTHOR

Damian Conway (damian AT conway.org)

๐Ÿ”ง MAINTENANCE

This package is maintained by Abigail (regexp-common AT abigail.be).

๐Ÿ› BUGS AND IRRITATIONS

Bound to be plenty.

For a start, there are many common regexes missing. Send them in to regexp-common AT abigail.be.

There are some POD issues when installing this module using a pre-5.6.0 perl; some manual pages may not install, or may not install correctly using a perl that is that old. You might consider upgrading your perl.

๐Ÿšซ NOT A BUG

๐Ÿ“„ LICENSE and COPYRIGHT

This software is Copyright (c) 2001 - 2017, Damian Conway and Abigail.

This module is free software, and maybe used under any of the following licenses:

  1. ๐Ÿ“œ The Perl Artistic License. See the file COPYRIGHT.AL.
  2. ๐Ÿ“œ The Perl Artistic License 2.0. See the file COPYRIGHT.AL2.
  3. ๐Ÿ“œ The BSD License. See the file COPYRIGHT.BSD.
  4. ๐Ÿ“œ The MIT License. See the file COPYRIGHT.MIT.
Regexp::Common
๐Ÿงฐ NAME ๐Ÿš€ Quick Reference ๐Ÿ“‹ SYNOPSIS ๐Ÿ“ DESCRIPTION
๐Ÿ” General syntax for requesting patterns ๐Ÿšฉ Flag syntax ๐ŸŒ Universal flags ๐Ÿ› ๏ธ OO interface and inline matching/substitution ๐Ÿ”ง Subroutine-based interface โž• Adding new regular expressions ๐Ÿ“ฆ Loading specific sets of patterns ๐Ÿ“‹ List of available patterns ๐Ÿ”ฎ Forthcoming patterns and features
๐Ÿฉบ DIAGNOSTICS ๐Ÿ™ ACKNOWLEDGEMENTS โœ๏ธ AUTHOR ๐Ÿ”ง MAINTENANCE ๐Ÿ› BUGS AND IRRITATIONS ๐Ÿšซ NOT A BUG ๐Ÿ“„ LICENSE and COPYRIGHT

Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-08 17:19 @216.73.216.150
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^