PERLREQUICK(1perl)
β¨ NAME β¨
perlrequick β the Perl regular expressions quick start, bestie edition π
π DESCRIPTION π
okay so this page is literally the very basics of understanding, creating and using regular expressions (aka 'regexes') in Perl. that's it, that's the vibe. π¦
πΈ The Guide πΈ
so this page is assuming you already know some stuff β like what a "pattern" is, and the basic syntax of how to use them. if you don't? no worries bestie, go read perlretut first π«Ά
π Simple word matching π
the simplest regex is literally just a word. or more generally, a string of characters. a regex made of a word matches any string that contains that word, periodt:
"Hello World" =~ /World/; # matches
in this statement, "World" is a regex, and the // wrapping it in /World/ is Perl's way of saying "hey, go search a string for a match." the =~ operator is the one that associates the string with the regex match, and it gives you a true value if the regex matched, or false if it didn't. in our case, "World" matches the second word in "Hello World", so the whole expression is true. this idea has several variations, and they're all iconic β¨
expressions like this are super useful in conditionals:
print "It matches\n" if "Hello World" =~ /World/;
you can flip the whole sense of the match with the !~ operator:
print "It doesn't match\n" if "Hello World" !~ /World/;
that literal string inside the regex can be replaced by a variable:
$greeting = "World";
print "It matches\n" if "Hello World" =~ /$greeting/;
and if you're matching against $_, you get to just... omit the "$_ =~" part. slay:
$_ = "Hello World";
print "It matches\n" if /World/;
finally, those // default delimiters for a match can be changed to literally any arbitrary delimiters by putting an 'm' out front:
"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
lowkey important: regexes have to match a part of the string exactly for the statement to be true. no partial credit, no vibes-based matching π
"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
Perl will always match at the earliest possible point in the string:
"Hello World" =~ /o/; # matches 'o' in 'Hello'
"That hat is red" =~ /hat/; # matches 'hat' in 'That'
now β not all characters can be used 'as is' in a match. some characters, called metacharacters, are considered special and reserved for regex notation. the metacharacters are:
{}[]()^$.|*+?\
a metacharacter can be matched literally by putting a backslash before it:
"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
in that last regex, the forward slash '/' is also backslashed, because it's being used to delimit the regex.
most of the metacharacters aren't always special, and other characters (like the ones delimiting the pattern) become special under various circumstances. this can be confusing and can absolutely lead to unexpected results. use re 'strict' can notify you of potential pitfalls. π«Ά
non-printable ASCII characters are represented by escape sequences. common examples are "\t" for a tab, "\n" for a newline, and "\r" for a carriage return. arbitrary bytes are represented by octal escape sequences, e.g., "\033", or hexadecimal escape sequences, e.g., "\x1B":
"1000\t2000" =~ m(0\t2) # matches
"cat" =~ /\143\x61\x74/ # matches in ASCII, but
# a weird way to spell cat
regexes are treated mostly as double-quoted strings, so variable substitution works:
$foo = 'house';
'cathouse' =~ /cat$foo/; # matches
'housecat' =~ /${foo}cat/; # matches
with all of the regexes above, if the regex matched anywhere in the string, it was considered a match. but to specify where it should match, we use the anchor metacharacters "^" and "$". the anchor "^" means match at the beginning of the string, and the anchor "$" means match at the end of the string β or before a newline at the end of the string. some examples:
"housekeeper" =~ /keeper/; # matches
"housekeeper" =~ /^keeper/; # doesn't match
"housekeeper" =~ /keeper$/; # matches
"housekeeper\n" =~ /keeper$/; # matches
"housekeeper" =~ /^housekeeper$/; # matches
π¦ Using character classes π¦
a character class lets a set of possible characters (instead of just one single character) match at a particular point in a regex. there are a number of different types of character classes, but usually when people say this term they mean the type described in this section, which is technically called "Bracketed character classes", because they're denoted by brackets "[...]", with the set of characters to be possibly matched inside. but we're gonna drop the "bracketed" below to match common usage. here are some examples of (bracketed) character classes:
/cat/; # matches 'cat'
/[bcr]at/; # matches 'bat', 'cat', or 'rat'
"abc" =~ /[cab]/; # matches 'a'
in that last statement, even though 'c' is the first character in the class, the earliest point at which the regex can match is 'a'.
/[yY][eE][sS]/; # match 'yes' in a case-insensitive way
# 'yes', 'Yes', 'YES', etc.
/yes/i; # also match 'yes' in a case-insensitive way
that last example shows a match with an 'i' modifier, which makes the match case-insensitive. obsessed π
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 "-]\^$" and are matched using an escape:
/[\]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'
the special character '-' acts as a range operator within character classes, so that the unwieldy "[0123456789]" and "[abc...xyz]" become the svelte "[0-9]" and "[a-z]":
/item[0-9]/; # matches 'item0' or ... or 'item9'
/[0-9a-fA-F]/; # matches a hexadecimal digit
if '-' is the first or last character in a character class, it's treated as an ordinary character.
the special character "^" in the first position of a character class denotes a negated character class, which matches any character but those in the brackets. both "[...]" and "[^...]" must match a character, or the match fails. so then:
/[^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
Perl has several abbreviations for common character classes. (quick note: these definitions are the ones Perl uses in ASCII-safe mode with the "/a" modifier. otherwise they could match many more non-ASCII Unicode characters too. see "Backslash sequences" in perlrecharclass for details.)
\dis a digit and represents
[0-9]
\sis a whitespace character and represents
[\ \t\r\n\f]
\wis a word character (alphanumeric or_) and represents
[0-9a-zA-Z_]
\Dis a negated\d; it represents any character but a digit
[^0-9]
\Sis a negated\s; it represents any non-whitespace character
[^\s]
\Wis a negated\w; it represents any non-word character
[^\w]
- the period
'.'matches any character but"\n"
the "\d\s\w\D\S\W" abbreviations can be used both inside and outside of character classes. here are some in use:
/\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.'
the word anchor "\b" matches a boundary between a word character and a non-word character "\w\W" or "\W\w":
$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
in that last example, the end of the string is considered a word boundary. ikyk β¨
for natural language processing (so that, for example, apostrophes are included in words), use "\b{wb}" instead:
"don't" =~ / .+? \b{wb} /x; # matches the whole string
π Matching this or that π
we can match different character strings with the alternation metacharacter '|'. to match "dog" or "cat", we form the regex "dog|cat". 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, "dog". if "dog" doesn't match, Perl will then try the next alternative, "cat". if "cat" doesn't match either, then the match fails and Perl moves to the next position in the string. some examples:
"cats and dogs" =~ /cat|dog|bird/; # matches "cat"
"cats and dogs" =~ /dog|cat|bird/; # matches "cat"
even though "dog" is the first alternative in that second regex, "cat" is able to match earlier in the string. main character energy from "cat" ngl π±
"cats" =~ /c|ca|cat|cats/; # matches "c"
"cats" =~ /cats|cat|ca|c/; # matches "cats"
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 one matches. simple as that π
π Grouping things and hierarchical matching π
the grouping metacharacters "()" 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 house(cat|keeper) means match "house" followed by either "cat" or "keeper". some more examples are
/(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
π Extracting matches π
Okay bestie, so those grouping metacharacters () we talked about? They're not just for vibes β they literally extract the parts of the string that matched. Every grouping you make drops the matched-inside bit into the special variables $1, $2, etc., and you can use those bad boys just like any other variable:
# extract hours, minutes, seconds
$time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
$hours = $1;
$minutes = $2;
$seconds = $3;
And in list context? A match /regex/ with groupings returns the whole list of matched values ($1,$2,...). So the above could also be written as:
($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
β¨ Now here's the tea on nesting: if your groupings are nested, $1 gets the group with the leftmost opening parenthesis, $2 gets the next opening parenthesis, and so on down the line. Example time β a complex regex with its matching variables labelled underneath:
/(ab(cd|ef)((gi)|j))/;
1 2 34
Riding alongside the matching variables $1, $2, ... are the backreferences \g1, \g2, ... β these are matching variables that you use inside a regex:
/(\w\w\w)\s\g1/; # find sequences like 'the the' in string
House rule, no exceptions: $1, $2, ... are for use outside a regex only, and \g1, \g2, ... are for inside a regex only. Don't mix them up, iykyk. π
π₯ Matching repetitions π₯
The quantifier metacharacters ?, *, +, and {} let us decide how many times a chunk of a regex has to repeat before we call it a match. Quantifiers go immediately after the character, character class, or grouping you're specifying. Their meanings, bestie:
a?= match 'a' 1 or 0 timesa*= match 'a' 0 or more times, i.e., any number of timesa+= match 'a' 1 or more times, i.e., at least oncea{n,m}= match at leastntimes, but not more thanmtimes.a{n,}= match at leastnor more timesa{,n}= matchntimes or fewer (Added in v5.34)a{n}= match exactlyntimes
Examples, because examples are the moment:
/[a-z]+\s+\d*/; # match a lowercase word, at least some space, and
# any number of digits
/(\w+)\s+\g1/; # 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
These quantifiers are greedy β they try to match as much of the string as possible while still letting the whole regex match. So we get this iconic behaviour:
$x = 'the cat in the hat';
$x =~ /^(.*)(at)(.*)$/; # matches,
# $1 = 'the cat in the h'
# $2 = 'at'
# $3 = '' (0 matches)
That first quantifier .* grabs as much of the string as it possibly can while keeping the regex happy. The second .* has literally no string left over, so it matches 0 times. Main character energy, honestly. π
πΈ More matching πΈ
A couple more things you might wanna know about matching operators, bestie.
The global modifier /g lets the matching operator match within a string as many times as possible. In scalar context, successive matches against a string will have /g hop from match to match, keeping track of where it's at in the string as it goes. You can get or set that position with the pos() function. Like so:
$x = "cat dog house"; # 3 words
while ($x =~ /(\w+)/g) {
print "Word is $1, ends at position ", pos $x, "\n";
}
which prints
Word is cat, ends at position 3
Word is dog, ends at position 7
Word is house, ends at position 13
A failed match or changing the target string resets that position. If you don't want the position reset after a failed match, add the /c, as in /regex/gc.
In list context, /g returns a list of matched groupings β or, if there are no groupings, a list of matches to the whole regex. So:
@words = ($x =~ /(\w+)/g); # matches,
# $word[0] = 'cat'
# $word[1] = 'dog'
# $word[2] = 'house'
π Search and replace π
Search and replace runs on s/regex/replacement/modifiers. The replacement is a Perl double-quoted string that swaps in for whatever got matched by the regex. The =~ operator shows up here too, to associate a string with s///. And if you're matching against $_, you can just drop the $_ =~ entirely. If there is a match, s/// returns the number of substitutions made; otherwise it returns false. Some examples:
$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"
With the s/// operator, those matched variables $1, $2, etc. are immediately available to use in the replacement expression. And with the global modifier, s///g will search and replace all occurrences of the regex in the string:
$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"
β¨ The non-destructive modifier s///r makes the result of the substitution get returned instead of modifying $_ (or whatever variable the substitute was bound to with =~):
$x = "I like dogs.";
$y = $x =~ s/dogs/cats/r;
print "$x $y\n"; # prints "I like dogs. I like cats."
$x = "Cats are great.";
print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
s/Frogs/Hedgehogs/r, "\n";
# prints "Hedgehogs are great."
@foo = map { s/[a-z]/X/r } qw(a b c 1 2 3);
# @foo is now qw(X X X 1 2 3)
π₯ The evaluation modifier s///e wraps an eval{...} around the replacement string, and the evaluated result is what gets substituted in for the matched substring. Some examples:
# 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"
That last example shows off the fact that s/// can use other delimiters, like s!!! and s{}{}, and even s{}//. And if single quotes get used β s''' β then the regex and the replacement both get treated as single-quoted strings. Cute, right? π¦
π§ The split operator π§
split /regex/, string splits string into a list of substrings and hands you that list back. The regex decides the character sequence that string gets split on. Example: to split a string into words, use
$x = "Calvin and Hobbes";
@word = split /\s+/, $x; # $word[0] = 'Calvin'
# $word[1] = 'and'
# $word[2] = 'Hobbes'
To pull out a comma-delimited list of numbers, use
$x = "1.618,2.718, 3.142";
@const = split /,\s*/, $x; # $const[0] = '1.618'
# $const[1] = '2.718'
# $const[2] = '3.142'
If you use the empty regex //, the string gets split into individual characters. And if the regex has groupings, then the list you get back also contains the matched substrings from those groupings:
$x = "/usr/bin";
@parts = split m!(/)!, $x; # $parts[0] = ''
# $parts[1] = '/'
# $parts[2] = 'usr'
# $parts[3] = '/'
# $parts[4] = 'bin'
Since the first character of $x matched the regex, split prepended an empty initial element to the list. Sneaky but correct. π
π "use re 'strict'" π
New in v5.22, this applies stricter rules than usual when compiling regular expression patterns. It can catch things that β while legal β may not actually be what you intended.
See 'strict' in re.
π BUGS π
None. (Iconic. We love a flawless queen. π)
π SEE ALSO π
This is just a quick start guide. For a more in-depth tutorial on regexes, see perlretut β and for the reference page, see perlre.
π AUTHOR AND COPYRIGHT π
Copyright (c) 2000 Mark Kvale All rights reserved.
This document may be distributed under the same terms as Perl itself.
πΈ Acknowledgments πΈ
The author would like to thank Mark-Jason Dominus, Tom Christiansen, Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful comments.
And that's a wrap, bestie! π«Ά This lil' gem is perl v5.44.0, dated 2026-10-17, and it lives at PERLREQUICK(1perl). Go forth and regex responsibly. πβ¨
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms