CINXE.COM
perlrequick - Perl regular expressions quick start - Perldoc Browser
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>perlrequick - Perl regular expressions quick start - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/perlrequick"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" /> <style> body { background: #f4f4f5; color: #020202; } .navbar-dark { background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%); background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%); background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0); background-repeat: repeat-x; } .navbar-dark .navbar-nav .nav-link, .navbar-dark .navbar-nav .nav-link:focus { color: #fff } .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 } #wrapperlicious { margin: 0 auto; font: 0.9em 'Helvetica Neue', Helvetica, sans-serif; font-weight: normal; line-height: 1.5em; margin: 0; padding: 0; } #wrapperlicious h1 { font-size: 1.5em } #wrapperlicious h2 { font-size: 1.3em } #wrapperlicious h3 { font-size: 1.1em } #wrapperlicious h4 { font-size: 0.9em } #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3, #wrapperlicious h4, #wrapperlicious dt { color: #020202; margin-top: 1em; margin-bottom: 1em; position: relative; font-weight: bold; } #wrapperlicious a { color: inherit; text-decoration: underline } #wrapperlicious #toc { text-decoration: none } #wrapperlicious a:hover { color: #2a2a2a } #wrapperlicious a img { border: 0 } #wrapperlicious :not(pre) > code { color: inherit; background-color: rgba(0, 0, 0, 0.04); border-radius: 3px; font: 0.9em Consolas, Menlo, Monaco, monospace; padding: 0.3em; } #wrapperlicious dd { margin: 0; margin-left: 2em; } #wrapperlicious dt { color: #2a2a2a; font-weight: bold; margin-left: 0.9em; } #wrapperlicious p { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious li > p { margin-bottom: 0; margin-top: 0; } #wrapperlicious pre { border: 1px solid #c1c1c1; border-radius: 3px; font: 100% Consolas, Menlo, Monaco, monospace; margin-bottom: 1em; margin-top: 1em; } #wrapperlicious pre > code { display: block; background-color: #f6f6f6; font: 0.9em Consolas, Menlo, Monaco, monospace; line-height: 1.5em; text-align: left; white-space: pre; padding: 1em; } #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious ul { list-style-type: square; } #wrapperlicious ul ul { margin-bottom: 0px; margin-top: 0px; } #footer { font-size: 0.8em; padding-top: 0.5em; text-align: center; } #more { display: inline; font-size: 0.8em; } #perldocdiv { background-color: #fff; border: 1px solid #c1c1c1; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; margin-left: auto; margin-right: auto; padding: 3em; padding-top: 1em; max-width: 960px; } #moduleversion { float: right } #wrapperlicious .leading-notice { font-style: italic; padding-left: 1em; margin-top: 1em; margin-bottom: 1em; } #wrapperlicious .permalink { display: none; left: -0.75em; position: absolute; padding-right: 0.25em; text-decoration: none; } #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink, #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink, #wrapperlicious dt:hover .permalink { display: block; } </style> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-KVNWBNT5FB'); gtag('config', 'UA-50555-3'); </script> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="/"><img src="/images/perl_camel_30.png" width="30" height="30" class="d-inline-block align-top" alt="Perl Camel Logo"> Perldoc Browser</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.8.4</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/perlrequick">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1/perlrequick">5.40.1</a> <a class="dropdown-item" href="/5.40.0/perlrequick">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3/perlrequick">5.38.3</a> <a class="dropdown-item" href="/5.38.2/perlrequick">5.38.2</a> <a class="dropdown-item" href="/5.38.1/perlrequick">5.38.1</a> <a class="dropdown-item" href="/5.38.0/perlrequick">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/perlrequick">5.36.3</a> <a class="dropdown-item" href="/5.36.2/perlrequick">5.36.2</a> <a class="dropdown-item" href="/5.36.1/perlrequick">5.36.1</a> <a class="dropdown-item" href="/5.36.0/perlrequick">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/perlrequick">5.34.3</a> <a class="dropdown-item" href="/5.34.2/perlrequick">5.34.2</a> <a class="dropdown-item" href="/5.34.1/perlrequick">5.34.1</a> <a class="dropdown-item" href="/5.34.0/perlrequick">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/perlrequick">5.32.1</a> <a class="dropdown-item" href="/5.32.0/perlrequick">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/perlrequick">5.30.3</a> <a class="dropdown-item" href="/5.30.2/perlrequick">5.30.2</a> <a class="dropdown-item" href="/5.30.1/perlrequick">5.30.1</a> <a class="dropdown-item" href="/5.30.0/perlrequick">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/perlrequick">5.28.3</a> <a class="dropdown-item" href="/5.28.2/perlrequick">5.28.2</a> <a class="dropdown-item" href="/5.28.1/perlrequick">5.28.1</a> <a class="dropdown-item" href="/5.28.0/perlrequick">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/perlrequick">5.26.3</a> <a class="dropdown-item" href="/5.26.2/perlrequick">5.26.2</a> <a class="dropdown-item" href="/5.26.1/perlrequick">5.26.1</a> <a class="dropdown-item" href="/5.26.0/perlrequick">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/perlrequick">5.24.4</a> <a class="dropdown-item" href="/5.24.3/perlrequick">5.24.3</a> <a class="dropdown-item" href="/5.24.2/perlrequick">5.24.2</a> <a class="dropdown-item" href="/5.24.1/perlrequick">5.24.1</a> <a class="dropdown-item" href="/5.24.0/perlrequick">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/perlrequick">5.22.4</a> <a class="dropdown-item" href="/5.22.3/perlrequick">5.22.3</a> <a class="dropdown-item" href="/5.22.2/perlrequick">5.22.2</a> <a class="dropdown-item" href="/5.22.1/perlrequick">5.22.1</a> <a class="dropdown-item" href="/5.22.0/perlrequick">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/perlrequick">5.20.3</a> <a class="dropdown-item" href="/5.20.2/perlrequick">5.20.2</a> <a class="dropdown-item" href="/5.20.1/perlrequick">5.20.1</a> <a class="dropdown-item" href="/5.20.0/perlrequick">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/perlrequick">5.18.4</a> <a class="dropdown-item" href="/5.18.3/perlrequick">5.18.3</a> <a class="dropdown-item" href="/5.18.2/perlrequick">5.18.2</a> <a class="dropdown-item" href="/5.18.1/perlrequick">5.18.1</a> <a class="dropdown-item" href="/5.18.0/perlrequick">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/perlrequick">5.16.3</a> <a class="dropdown-item" href="/5.16.2/perlrequick">5.16.2</a> <a class="dropdown-item" href="/5.16.1/perlrequick">5.16.1</a> <a class="dropdown-item" href="/5.16.0/perlrequick">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/perlrequick">5.14.4</a> <a class="dropdown-item" href="/5.14.3/perlrequick">5.14.3</a> <a class="dropdown-item" href="/5.14.2/perlrequick">5.14.2</a> <a class="dropdown-item" href="/5.14.1/perlrequick">5.14.1</a> <a class="dropdown-item" href="/5.14.0/perlrequick">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/perlrequick">5.12.5</a> <a class="dropdown-item" href="/5.12.4/perlrequick">5.12.4</a> <a class="dropdown-item" href="/5.12.3/perlrequick">5.12.3</a> <a class="dropdown-item" href="/5.12.2/perlrequick">5.12.2</a> <a class="dropdown-item" href="/5.12.1/perlrequick">5.12.1</a> <a class="dropdown-item" href="/5.12.0/perlrequick">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/perlrequick">5.10.1</a> <a class="dropdown-item" href="/5.10.0/perlrequick">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/perlrequick">5.8.9</a> <a class="dropdown-item" href="/5.8.8/perlrequick">5.8.8</a> <a class="dropdown-item" href="/5.8.7/perlrequick">5.8.7</a> <a class="dropdown-item" href="/5.8.6/perlrequick">5.8.6</a> <a class="dropdown-item" href="/5.8.5/perlrequick">5.8.5</a> <a class="dropdown-item active" href="/5.8.4/perlrequick">5.8.4</a> <a class="dropdown-item" href="/5.8.3/perlrequick">5.8.3</a> <a class="dropdown-item" href="/5.8.2/perlrequick">5.8.2</a> <a class="dropdown-item" href="/5.8.1/perlrequick">5.8.1</a> <a class="dropdown-item" href="/5.8.0/perlrequick">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/perlrequick">5.6.2</a> <a class="dropdown-item" href="/5.6.1/perlrequick">5.6.1</a> <a class="dropdown-item" href="/5.6.0/perlrequick">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/perlrequick">5.005_04</a> <a class="dropdown-item" href="/5.005_03/perlrequick">5.005_03</a> <a class="dropdown-item" href="/5.005_02/perlrequick">5.005_02</a> <a class="dropdown-item" href="/5.005_01/perlrequick">5.005_01</a> <a class="dropdown-item" href="/5.005/perlrequick">5.005</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-dev"> <a class="dropdown-item" href="/blead/perlrequick">blead</a> <a class="dropdown-item" href="/5.41.10/perlrequick">5.41.10</a> <a class="dropdown-item" href="/5.41.9/perlrequick">5.41.9</a> <a class="dropdown-item" href="/5.41.8/perlrequick">5.41.8</a> <a class="dropdown-item" href="/5.41.7/perlrequick">5.41.7</a> <a class="dropdown-item" href="/5.41.6/perlrequick">5.41.6</a> <a class="dropdown-item" href="/5.41.5/perlrequick">5.41.5</a> <a class="dropdown-item" href="/5.41.4/perlrequick">5.41.4</a> <a class="dropdown-item" href="/5.41.3/perlrequick">5.41.3</a> <a class="dropdown-item" href="/5.41.2/perlrequick">5.41.2</a> <a class="dropdown-item" href="/5.41.1/perlrequick">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1-RC1/perlrequick">5.40.1-RC1</a> <a class="dropdown-item" href="/5.40.0-RC2/perlrequick">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/perlrequick">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/perlrequick">5.39.10</a> <a class="dropdown-item" href="/5.39.9/perlrequick">5.39.9</a> <a class="dropdown-item" href="/5.39.8/perlrequick">5.39.8</a> <a class="dropdown-item" href="/5.39.7/perlrequick">5.39.7</a> <a class="dropdown-item" href="/5.39.6/perlrequick">5.39.6</a> <a class="dropdown-item" href="/5.39.5/perlrequick">5.39.5</a> <a class="dropdown-item" href="/5.39.4/perlrequick">5.39.4</a> <a class="dropdown-item" href="/5.39.3/perlrequick">5.39.3</a> <a class="dropdown-item" href="/5.39.2/perlrequick">5.39.2</a> <a class="dropdown-item" href="/5.39.1/perlrequick">5.39.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3-RC1/perlrequick">5.38.3-RC1</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-nav"> <a class="dropdown-item" href="/5.8.4/perl">Perl</a> <a class="dropdown-item" href="/5.8.4/perlintro">Intro</a> <a class="dropdown-item" href="/5.8.4/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/5.8.4/perlfaq">FAQs</a> <a class="dropdown-item" href="/5.8.4/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.4/perlop">Operators</a> <a class="dropdown-item" href="/5.8.4/functions">Functions</a> <a class="dropdown-item" href="/5.8.4/variables">Variables</a> <a class="dropdown-item" href="/5.8.4/modules">Modules</a> <a class="dropdown-item" href="/5.8.4/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.4/perldelta">Release Notes</a> <a class="dropdown-item" href="/5.8.4/perlcommunity">Community</a> <a class="dropdown-item" href="/5.8.4/perlhist">History</a> </div> </li> </ul> <ul class="navbar-nav"> <script> function set_expand (expand) { var perldocdiv = document.getElementById('perldocdiv'); var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width'); var expanded = (width == '' || width == 'none') ? true : false; if (expand === null) { expand = !expanded; } if ((expand && !expanded) || (!expand && expanded)) { perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px'); var button_classlist = document.getElementById('content-expand-button').classList; if (expand) { button_classlist.add('btn-light'); button_classlist.remove('btn-outline-light'); } else { button_classlist.add('btn-outline-light'); button_classlist.remove('btn-light'); } } return expand; } function toggle_expand () { var expand = set_expand(null); document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC'; } function read_expand () { return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { if (read_expand()) { set_expand(true); } }); } else if (read_expand()) { set_expand(true); } </script> <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-4" onclick="toggle_expand()">Expand</button> </ul> <form class="form-inline" method="get" action="/5.8.4/search"> <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search" value=""> </form> </div> </nav> <div id="wrapperlicious" class="container-fluid"> <div id="perldocdiv"> <div id="links"> <a href="/5.8.4/perlrequick">perlrequick</a> <div id="more"> (<a href="/5.8.4/perlrequick.txt">source</a>, <a href="https://metacpan.org/pod/perlrequick">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl 5.8.4. <a href="/perlrequick">View the latest version</a> </div> <h1><a id="toc">CONTENTS</a></h1> <ul> <li> <a class="text-decoration-none" href="#NAME">NAME</a> </li> <li> <a class="text-decoration-none" href="#DESCRIPTION">DESCRIPTION</a> </li> <li> <a class="text-decoration-none" href="#The-Guide">The Guide</a> <ul> <li> <a class="text-decoration-none" href="#Simple-word-matching">Simple word matching</a> </li> <li> <a class="text-decoration-none" href="#Using-character-classes">Using character classes</a> </li> <li> <a class="text-decoration-none" href="#Matching-this-or-that">Matching this or that</a> </li> <li> <a class="text-decoration-none" href="#Grouping-things-and-hierarchical-matching">Grouping things and hierarchical matching</a> </li> <li> <a class="text-decoration-none" href="#Extracting-matches">Extracting matches</a> </li> <li> <a class="text-decoration-none" href="#Matching-repetitions">Matching repetitions</a> </li> <li> <a class="text-decoration-none" href="#More-matching">More matching</a> </li> <li> <a class="text-decoration-none" href="#Search-and-replace">Search and replace</a> </li> <li> <a class="text-decoration-none" href="#The-split-operator">The split operator</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#BUGS">BUGS</a> </li> <li> <a class="text-decoration-none" href="#SEE-ALSO">SEE ALSO</a> </li> <li> <a class="text-decoration-none" href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a> <ul> <li> <a class="text-decoration-none" href="#Acknowledgments">Acknowledgments</a> </li> </ul> </li> </ul> <h1 id="NAME"><a class="permalink" href="#NAME">#</a>NAME</h1> <p>perlrequick - Perl regular expressions quick start</p> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl.</p> <h1 id="The-Guide"><a class="permalink" href="#The-Guide">#</a><a id="The"></a>The Guide</h1> <h2 id="Simple-word-matching"><a class="permalink" href="#Simple-word-matching">#</a><a id="Simple"></a>Simple word matching</h2> <p>The simplest regex is simply a word, or more generally, a string of characters. A regex consisting of a word matches any string that contains that word:</p> <pre><code>"Hello World" =~ /World/; # matches</code></pre> <p>In this statement, <code>World</code> is a regex and the <code>//</code> enclosing <code>/World/</code> tells perl to search a string for a match. The operator <code>=~</code> associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, <code>World</code> matches the second word in <code>"Hello World"</code>, so the expression is true. This idea has several variations.</p> <p>Expressions like this are useful in conditionals:</p> <pre><code>print "It matches\n" if "Hello World" =~ /World/;</code></pre> <p>The sense of the match can be reversed by using <code>!~</code> operator:</p> <pre><code>print "It doesn't match\n" if "Hello World" !~ /World/;</code></pre> <p>The literal string in the regex can be replaced by a variable:</p> <pre><code>$greeting = "World"; print "It matches\n" if "Hello World" =~ /$greeting/;</code></pre> <p>If you're matching against <code>$_</code>, the <code>$_ =~</code> part can be omitted:</p> <pre><code>$_ = "Hello World"; print "It matches\n" if /World/;</code></pre> <p>Finally, the <code>//</code> default delimiters for a match can be changed to arbitrary delimiters by putting an <code>'m'</code> out front:</p> <pre><code>"Hello World" =~ m!World!; # matches, delimited by '!' "Hello World" =~ m{World}; # matches, note the matching '{}' "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin', # '/' becomes an ordinary char</code></pre> <p>Regexes must match a part of the string <i>exactly</i> in order for the statement to be true:</p> <pre><code>"Hello World" =~ /world/; # doesn't match, case sensitive "Hello World" =~ /o W/; # matches, ' ' is an ordinary char "Hello World" =~ /World /; # doesn't match, no ' ' at end</code></pre> <p>perl will always match at the earliest possible point in the string:</p> <pre><code>"Hello World" =~ /o/; # matches 'o' in 'Hello' "That hat is red" =~ /hat/; # matches 'hat' in 'That'</code></pre> <p>Not all characters can be used 'as is' in a match. Some characters, called <b>metacharacters</b>, are reserved for use in regex notation. The metacharacters are</p> <pre><code class="plaintext">{}[]()^$.|*+?\</code></pre> <p>A metacharacter can be matched by putting a backslash before it:</p> <pre><code>"2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter "2+2=4" =~ /2\+2/; # matches, \+ is treated like an ordinary + 'C:\WIN32' =~ /C:\\WIN/; # matches "/usr/bin/perl" =~ /\/usr\/bin\/perl/; # matches</code></pre> <p>In the last regex, the forward slash <code>'/'</code> is also backslashed, because it is used to delimit the regex.</p> <p>Non-printable ASCII characters are represented by <b>escape sequences</b>. Common examples are <code>\t</code> for a tab, <code>\n</code> for a newline, and <code>\r</code> for a carriage return. Arbitrary bytes are represented by octal escape sequences, e.g., <code>\033</code>, or hexadecimal escape sequences, e.g., <code>\x1B</code>:</p> <pre><code class="plaintext">"1000\t2000" =~ m(0\t2) # matches "cat" =~ /\143\x61\x74/ # matches, but a weird way to spell cat</code></pre> <p>Regexes are treated mostly as double quoted strings, so variable substitution works:</p> <pre><code>$foo = 'house'; 'cathouse' =~ /cat$foo/; # matches 'housecat' =~ /${foo}cat/; # matches</code></pre> <p>With all of the regexes above, if the regex matched anywhere in the string, it was considered a match. To specify <i>where</i> it should match, we would use the <b>anchor</b> metacharacters <code>^</code> and <code>$</code>. The anchor <code>^</code> means match at the beginning of the string and the anchor <code>$</code> means match at the end of the string, or before a newline at the end of the string. Some examples:</p> <pre><code>"housekeeper" =~ /keeper/; # matches "housekeeper" =~ /^keeper/; # doesn't match "housekeeper" =~ /keeper$/; # matches "housekeeper\n" =~ /keeper$/; # matches "housekeeper" =~ /^housekeeper$/; # matches</code></pre> <h2 id="Using-character-classes"><a class="permalink" href="#Using-character-classes">#</a><a id="Using"></a>Using character classes</h2> <p>A <b>character class</b> allows a set of possible characters, rather than just a single character, to match at a particular point in a regex. Character classes are denoted by brackets <code>[...]</code>, with the set of characters to be possibly matched inside. Here are some examples:</p> <pre><code>/cat/; # matches 'cat' /[bcr]at/; # matches 'bat', 'cat', or 'rat' "abc" =~ /[cab]/; # matches 'a'</code></pre> <p>In the last statement, even though <code>'c'</code> is the first character in the class, the earliest point at which the regex can match is <code>'a'</code>.</p> <pre><code>/[yY][eE][sS]/; # match 'yes' in a case-insensitive way # 'yes', 'Yes', 'YES', etc. /yes/i; # also match 'yes' in a case-insensitive way</code></pre> <p>The last example shows a match with an <code>'i'</code> <b>modifier</b>, which makes the match case-insensitive.</p> <p>Character classes also have ordinary and special characters, but the sets of ordinary and special characters inside a character class are different than those outside a character class. The special characters for a character class are <code>-]\^$</code> and are matched using an escape:</p> <pre><code>/[\]c]def/; # matches ']def' or 'cdef' $x = 'bcr'; /[$x]at/; # matches 'bat, 'cat', or 'rat' /[\$x]at/; # matches '$at' or 'xat' /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'</code></pre> <p>The special character <code>'-'</code> acts as a range operator within character classes, so that the unwieldy <code>[0123456789]</code> and <code>[abc...xyz]</code> become the svelte <code>[0-9]</code> and <code>[a-z]</code>:</p> <pre><code>/item[0-9]/; # matches 'item0' or ... or 'item9' /[0-9a-fA-F]/; # matches a hexadecimal digit</code></pre> <p>If <code>'-'</code> is the first or last character in a character class, it is treated as an ordinary character.</p> <p>The special character <code>^</code> in the first position of a character class denotes a <b>negated character class</b>, which matches any character but those in the brackets. Both <code>[...]</code> and <code>[^...]</code> must match a character, or the match fails. Then</p> <pre><code>/[^a]at/; # doesn't match 'aat' or 'at', but matches # all other 'bat', 'cat, '0at', '%at', etc. /[^0-9]/; # matches a non-numeric character /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary</code></pre> <p>Perl has several abbreviations for common character classes:</p> <ul> <li><p>\d is a digit and represents</p> <pre><code class="plaintext">[0-9]</code></pre> </li> <li><p>\s is a whitespace character and represents</p> <pre><code class="plaintext">[\ \t\r\n\f]</code></pre> </li> <li><p>\w is a word character (alphanumeric or _) and represents</p> <pre><code class="plaintext">[0-9a-zA-Z_]</code></pre> </li> <li><p>\D is a negated \d; it represents any character but a digit</p> <pre><code class="plaintext">[^0-9]</code></pre> </li> <li><p>\S is a negated \s; it represents any non-whitespace character</p> <pre><code class="plaintext">[^\s]</code></pre> </li> <li><p>\W is a negated \w; it represents any non-word character</p> <pre><code class="plaintext">[^\w]</code></pre> </li> <li><p>The period '.' matches any character but "\n"</p> </li> </ul> <p>The <code>\d\s\w\D\S\W</code> abbreviations can be used both inside and outside of character classes. Here are some in use:</p> <pre><code>/\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format /[\d\s]/; # matches any digit or whitespace character /\w\W\w/; # matches a word char, followed by a # non-word char, followed by a word char /..rt/; # matches any two chars, followed by 'rt' /end\./; # matches 'end.' /end[.]/; # same thing, matches 'end.'</code></pre> <p>The <span style="white-space: nowrap;"><b>word anchor</b> </span> <code>\b</code> matches a boundary between a word character and a non-word character <code>\w\W</code> or <code>\W\w</code>:</p> <pre><code>$x = "Housecat catenates house and cat"; $x =~ /\bcat/; # matches cat in 'catenates' $x =~ /cat\b/; # matches cat in 'housecat' $x =~ /\bcat\b/; # matches 'cat' at end of string</code></pre> <p>In the last example, the end of the string is considered a word boundary.</p> <h2 id="Matching-this-or-that"><a class="permalink" href="#Matching-this-or-that">#</a><a id="Matching"></a>Matching this or that</h2> <p>We can match different character strings with the <b>alternation</b> metacharacter <code>'|'</code>. To match <code>dog</code> or <code>cat</code>, we form the regex <code>dog|cat</code>. As before, perl will try to match the regex at the earliest possible point in the string. At each character position, perl will first try to match the first alternative, <code>dog</code>. If <code>dog</code> doesn't match, perl will then try the next alternative, <code>cat</code>. If <code>cat</code> doesn't match either, then the match fails and perl moves to the next position in the string. Some examples:</p> <pre><code>"cats and dogs" =~ /cat|dog|bird/; # matches "cat" "cats and dogs" =~ /dog|cat|bird/; # matches "cat"</code></pre> <p>Even though <code>dog</code> is the first alternative in the second regex, <code>cat</code> is able to match earlier in the string.</p> <pre><code>"cats" =~ /c|ca|cat|cats/; # matches "c" "cats" =~ /cats|cat|ca|c/; # matches "cats"</code></pre> <p>At a given character position, the first alternative that allows the regex match to succeed will be the one that matches. Here, all the alternatives match at the first string position, so the first matches.</p> <h2 id="Grouping-things-and-hierarchical-matching"><a class="permalink" href="#Grouping-things-and-hierarchical-matching">#</a><a id="Grouping"></a>Grouping things and hierarchical matching</h2> <p>The <b>grouping</b> metacharacters <code>()</code> allow a part of a regex to be treated as a single unit. Parts of a regex are grouped by enclosing them in parentheses. The regex <code>house(cat|keeper)</code> means match <code>house</code> followed by either <code>cat</code> or <code>keeper</code>. Some more examples are</p> <pre><code>/(a|b)b/; # matches 'ab' or 'bb' /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere /house(cat|)/; # matches either 'housecat' or 'house' /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or # 'house'. Note groups can be nested. "20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d', # because '20\d\d' can't match</code></pre> <h2 id="Extracting-matches"><a class="permalink" href="#Extracting-matches">#</a><a id="Extracting"></a>Extracting matches</h2> <p>The grouping metacharacters <code>()</code> also allow the extraction of the parts of a string that matched. For each grouping, the part that matched inside goes into the special variables <code>$1</code>, <code>$2</code>, etc. They can be used just as ordinary variables:</p> <pre><code># extract hours, minutes, seconds $time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format $hours = $1; $minutes = $2; $seconds = $3;</code></pre> <p>In list context, a match <code>/regex/</code> with groupings will return the list of matched values <code>($1,$2,...)</code>. So we could rewrite it as</p> <pre><code>($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);</code></pre> <p>If the groupings in a regex are nested, <code>$1</code> gets the group with the leftmost opening parenthesis, <code>$2</code> the next opening parenthesis, etc. For example, here is a complex regex and the matching variables indicated below it:</p> <pre><code>/(ab(cd|ef)((gi)|j))/; 1 2 34</code></pre> <p>Associated with the matching variables <code>$1</code>, <code>$2</code>, ... are the <b>backreferences</b> <code>\1</code>, <code>\2</code>, ... Backreferences are matching variables that can be used <i>inside</i> a regex:</p> <pre><code>/(\w\w\w)\s\1/; # find sequences like 'the the' in string</code></pre> <p><code>$1</code>, <code>$2</code>, ... should only be used outside of a regex, and <code>\1</code>, <code>\2</code>, ... only inside a regex.</p> <h2 id="Matching-repetitions"><a class="permalink" href="#Matching-repetitions">#</a><a id="Matching1"></a>Matching repetitions</h2> <p>The <b>quantifier</b> metacharacters <code>?</code>, <code>*</code>, <code>+</code>, and <code>{}</code> allow us to determine the number of repeats of a portion of a regex we consider to be a match. Quantifiers are put immediately after the character, character class, or grouping that we want to specify. They have the following meanings:</p> <ul> <li><p><code>a?</code> = match 'a' 1 or 0 times</p> </li> <li><p><code>a*</code> = match 'a' 0 or more times, i.e., any number of times</p> </li> <li><p><code>a+</code> = match 'a' 1 or more times, i.e., at least once</p> </li> <li><p><code>a{n,m}</code> = match at least <code>n</code> times, but not more than <code>m</code> times.</p> </li> <li><p><code>a{n,}</code> = match at least <code>n</code> or more times</p> </li> <li><p><code>a{n}</code> = match exactly <code>n</code> times</p> </li> </ul> <p>Here are some examples:</p> <pre><code>/[a-z]+\s+\d*/; # match a lowercase word, at least some space, and # any number of digits /(\w+)\s+\1/; # match doubled words of arbitrary length $year =~ /\d{2,4}/; # make sure year is at least 2 but not more # than 4 digits $year =~ /\d{4}|\d{2}/; # better match; throw out 3 digit dates</code></pre> <p>These quantifiers will try to match as much of the string as possible, while still allowing the regex to match. So we have</p> <pre><code>$x = 'the cat in the hat'; $x =~ /^(.*)(at)(.*)$/; # matches, # $1 = 'the cat in the h' # $2 = 'at' # $3 = '' (0 matches)</code></pre> <p>The first quantifier <code>.*</code> grabs as much of the string as possible while still having the regex match. The second quantifier <code>.*</code> has no string left to it, so it matches 0 times.</p> <h2 id="More-matching"><a class="permalink" href="#More-matching">#</a><a id="More"></a>More matching</h2> <p>There are a few more things you might want to know about matching operators. In the code</p> <pre><code>$pattern = 'Seuss'; while (<>) { print if /$pattern/; }</code></pre> <p>perl has to re-evaluate <code>$pattern</code> each time through the loop. If <code>$pattern</code> won't be changing, use the <code>//o</code> modifier, to only perform variable substitutions once. If you don't want any substitutions at all, use the special delimiter <code>m''</code>:</p> <pre><code>@pattern = ('Seuss'); m/@pattern/; # matches 'Seuss' m'@pattern'; # matches the literal string '@pattern'</code></pre> <p>The global modifier <code>//g</code> allows the matching operator to match within a string as many times as possible. In scalar context, successive matches against a string will have <code>//g</code> jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the <code>pos()</code> function. For example,</p> <pre><code>$x = "cat dog house"; # 3 words while ($x =~ /(\w+)/g) { print "Word is $1, ends at position ", pos $x, "\n"; }</code></pre> <p>prints</p> <pre><code class="plaintext">Word is cat, ends at position 3 Word is dog, ends at position 7 Word is house, ends at position 13</code></pre> <p>A failed match or changing the target string resets the position. If you don't want the position reset after failure to match, add the <code>//c</code>, as in <code>/regex/gc</code>.</p> <p>In list context, <code>//g</code> returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regex. So</p> <pre><code>@words = ($x =~ /(\w+)/g); # matches, # $word[0] = 'cat' # $word[1] = 'dog' # $word[2] = 'house'</code></pre> <h2 id="Search-and-replace"><a class="permalink" href="#Search-and-replace">#</a><a id="Search"></a>Search and replace</h2> <p>Search and replace is performed using <code>s/regex/replacement/modifiers</code>. The <code>replacement</code> is a Perl double quoted string that replaces in the string whatever is matched with the <code>regex</code>. The operator <code>=~</code> is also used here to associate a string with <code>s///</code>. If matching against <code>$_</code>, the <span style="white-space: nowrap;"><code>$_ =~</code> </span> can be dropped. If there is a match, <code>s///</code> returns the number of substitutions made, otherwise it returns false. Here are a few examples:</p> <pre><code>$x = "Time to feed the cat!"; $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!" $y = "'quoted words'"; $y =~ s/^'(.*)'$/$1/; # strip single quotes, # $y contains "quoted words"</code></pre> <p>With the <code>s///</code> operator, the matched variables <code>$1</code>, <code>$2</code>, etc. are immediately available for use in the replacement expression. With the global modifier, <code>s///g</code> will search and replace all occurrences of the regex in the string:</p> <pre><code>$x = "I batted 4 for 4"; $x =~ s/4/four/; # $x contains "I batted four for 4" $x = "I batted 4 for 4"; $x =~ s/4/four/g; # $x contains "I batted four for four"</code></pre> <p>The evaluation modifier <code>s///e</code> wraps an <code>eval{...}</code> around the replacement string and the evaluated result is substituted for the matched substring. Some examples:</p> <pre><code># reverse all the words in a string $x = "the cat in the hat"; $x =~ s/(\w+)/reverse $1/ge; # $x contains "eht tac ni eht tah" # convert percentage to decimal $x = "A 39% hit rate"; $x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"</code></pre> <p>The last example shows that <code>s///</code> can use other delimiters, such as <code>s!!!</code> and <code>s{}{}</code>, and even <code>s{}//</code>. If single quotes are used <code>s'''</code>, then the regex and replacement are treated as single quoted strings.</p> <h2 id="The-split-operator"><a class="permalink" href="#The-split-operator">#</a><a id="The1"></a>The split operator</h2> <p><code>split /regex/, string</code> splits <code>string</code> into a list of substrings and returns that list. The regex determines the character sequence that <code>string</code> is split with respect to. For example, to split a string into words, use</p> <pre><code>$x = "Calvin and Hobbes"; @word = split /\s+/, $x; # $word[0] = 'Calvin' # $word[1] = 'and' # $word[2] = 'Hobbes'</code></pre> <p>To extract a comma-delimited list of numbers, use</p> <pre><code>$x = "1.618,2.718, 3.142"; @const = split /,\s*/, $x; # $const[0] = '1.618' # $const[1] = '2.718' # $const[2] = '3.142'</code></pre> <p>If the empty regex <code>//</code> is used, the string is split into individual characters. If the regex has groupings, then the list produced contains the matched substrings from the groupings as well:</p> <pre><code>$x = "/usr/bin"; @parts = split m!(/)!, $x; # $parts[0] = '' # $parts[1] = '/' # $parts[2] = 'usr' # $parts[3] = '/' # $parts[4] = 'bin'</code></pre> <p>Since the first character of $x matched the regex, <code>split</code> prepended an empty initial element to the list.</p> <h1 id="BUGS"><a class="permalink" href="#BUGS">#</a>BUGS</h1> <p>None.</p> <h1 id="SEE-ALSO"><a class="permalink" href="#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1> <p>This is just a quick start guide. For a more in-depth tutorial on regexes, see <a href="/5.8.4/perlretut">perlretut</a> and for the reference page, see <a href="/5.8.4/perlre">perlre</a>.</p> <h1 id="AUTHOR-AND-COPYRIGHT"><a class="permalink" href="#AUTHOR-AND-COPYRIGHT">#</a><a id="AUTHOR"></a>AUTHOR AND COPYRIGHT</h1> <p>Copyright (c) 2000 Mark Kvale All rights reserved.</p> <p>This document may be distributed under the same terms as Perl itself.</p> <h2 id="Acknowledgments"><a class="permalink" href="#Acknowledgments">#</a>Acknowledgments</h2> <p>The author would like to thank Mark-Jason Dominus, Tom Christiansen, Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful comments.</p> </div> <div id="footer"> <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p> <p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="/js/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>