PERLREQUICK(1)

✨ NAME ✨

perlrequick β€” Perl regular expressions quick start, bestie edition πŸ’–


πŸŽ€ DESCRIPTION πŸŽ€

okay so this page is literally just the very basics of understanding, creating, and using regular expressions (aka "regexes") in Perl. that's it, that's the vibe. no cap. πŸ¦‹


🌸 The Guide 🌸

so, this page is assuming you already know some stuff β€” like what a "pattern" is, and the basic syntax of using them. if you don't? no worries babe, go read perlretut instead. 🫢


✨ Simple word matching ✨

the simplest regex is literally just a word. or, more generally, a string of characters. a regex that's made of a word matches any string that contains that word:

"Hello World" =~ /World/;  # matches

in this statement, "World" is a regex, and the // wrapping around it in /World/ is Perl's way of being like "hey, search this string for a match". the operator =~ is what pairs the string up with the regex match, and it gives you back a true value if the regex matched, or false if it didn't. in our little example, "World" matches the second word in "Hello World", so the whole expression is true. and this idea? it comes in several variations, naturally. πŸ’…

expressions like this are super useful in conditionals:

print "It matches\n" if "Hello World" =~ /World/;

you can also flip the whole sense of the match by using the !~ operator:

print "It doesn't match\n" if "Hello World" !~ /World/;

that literal string sitting inside the regex can be swapped out for a variable:

$greeting = "World";
print "It matches\n" if "Hello World" =~ /$greeting/;

and if you're matching against $_, you can just... drop the $_ =~ part entirely. it's giving minimal effort, iconic:

$_ = "Hello World";
print "It matches\n" if /World/;

finally, those // default delimiters for a match can be changed to literally whatever delimiters you want, just 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

now listen β€” regexes have to match a part of the string exactly for the statement to come out true:

"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. always. it's committed like that:

"Hello World" =~ /o/;       # matches 'o' in 'Hello'
"That hat is red" =~ /hat/; # matches 'hat' in 'That'

⚠️ okay so 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 in front of 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 / also got backslashed, because it's being used to delimit the regex. iykyk. πŸ™ˆ

most of the metacharacters aren't always special, and other characters (like the ones delimiting the pattern) become special under various circumstances. this can get confusing and lead to unexpected results, fr fr. good news though: use re 'strict' can notify you of potential pitfalls. πŸ‘‘

non-printable ASCII characters get represented by escape sequences. common ones are "\t" for a tab, "\n" for a newline, and "\r" for a carriage return. arbitrary bytes get 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, which means variable substitution totally works:

$foo = 'house';
'cathouse' =~ /cat$foo/;   # matches
'housecat' =~ /${foo}cat/; # matches

okay so with literally every regex above, if the regex matched anywhere in the string, it counted as a match. but what if you wanna specify where it should match? that's where the anchor metacharacters "^" and "$" come in. 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 whole set</> of possible characters match at a particular point in a regex, instead of just one single character. there are a bunch of different types of character classes, but usually when people say this term, they mean the type described in this section β€” which are technically called "Bracketed character classes", because they're denoted by brackets [...], with the set of characters to be possibly matched sitting inside. but we're gonna drop the "bracketed" from here on out, 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. slay.

character classes also have ordinary and special characters β€” but the sets of ordinary and special characters inside a character class are different from those outside one. the special characters for a character class are -]\^$ and they get 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 inside 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. cute.

the special character "^" in the first position of a character class denotes a negated character class, which matches any character but the ones in the brackets. and heads up: 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. (these definitions are the ones Perl uses in ASCII-safe mode with the "/a" modifier. otherwise they could match a whole lot more non-ASCII Unicode characters too. see "Backslash sequences" in perlrecharclass for the details.) πŸ‘‘

  • \d is a digit and represents
[0-9]
  • \s is a whitespace character and represents
[\ \t\r\n\f]
  • \w is a word character (alphanumeric or _) and represents
[0-9a-zA-Z_]
  • \D is a negated \d; it represents any character but a digit
[^0-9]
  • \S is a negated \s; it represents any non-whitespace character
[^\s]
  • \W is 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. periodt. πŸ’…

and for natural language processing (so that, for example, apostrophes get 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 using 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". and if "cat" doesn't match either, then the match fails and Perl moves on 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. the math is mathing. 😌

"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 is the one that matches. here, all the alternatives match at the first string position, so the first one wins. πŸ†


πŸ‘‘ Grouping things and hierarchical matching πŸ‘‘

the grouping metacharacters "()" let a part of a regex 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 () aren't just for vibes β€” they literally let you extract the parts of a string that matched. Every grouping you make drops the matched bit inside into the special variables $1, $2, etc. And those? They're just regular variables, no special handling needed:

# extract hours, minutes, seconds
$time =~ /(\d\d):(\d\d):(\d\d)/;  # match hh:mm:ss format
$hours = $1;
$minutes = $2;
$seconds = $3;

And if you're in list context? A match /regex/ with groupings returns the whole list of matched values ($1,$2,...). So that same thing could be written as:

($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);

Now, when your groupings are nested, the numbering goes by the leftmost opening parenthesis first: $1 gets the group with the leftmost opening parenthesis, $2 gets the next opening parenthesis, and so on. Check out this complex regex with its matching variables labeled underneath:

/(ab(cd|ef)((gi)|j))/;
 1  2      34

And you know what pairs with the matching variables $1, $2, ...? The backreferences \g1, \g2, ... 🫢 These are matching variables you can actually use inside a regex:

/(\w\w\w)\s\g1/; # find sequences like 'the the' in string
🚨 Real talk though: $1, $2, ... are only for outside a regex, and \g1, \g2, ... are only for inside a regex. Don't mix them up, iykyk.

✨ Matching repetitions ✨

The quantifier metacharacters ?, *, +, and {} are how we say how many times a portion of a regex can repeat and still count as a match. You drop a quantifier immediately after the character, character class, or grouping you're specifying. Meanings, bestie:

  • a? = match 'a' 1 or 0 times
  • a* = match 'a' 0 or more times, i.e., any number of times
  • a+ = match 'a' 1 or more times, i.e., at least once
  • a{n,m} = match at least n times, but not more than m times.
  • a{n,} = match at least n or more times
  • a{,n} = match n times or fewer (Added in v5.34)
  • a{n} = match exactly n times

Some examples, because examples are iconic:

/[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:

$x = 'the cat in the hat';
$x =~ /^(.*)(at)(.*)$/; # matches,
                        # $1 = 'the cat in the h'
                        # $2 = 'at'
                        # $3 = ''   (0 matches)

See how the first quantifier .* grabs as much of the string as possible while still having the regex match? And the second quantifier .* has no string left to it, so it matches 0 times. No cap. πŸ’…


🌈 More matching 🌈

A few 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 jump from match to match, keeping track of position in the string as it goes along. You can get or set that position with the pos() function. For example:

$x = "cat dog house"; # 3 words
while ($x =~ /(\w+)/g) {
    print "Word is $1, ends at position ", pos $x, "\n";
}

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 the position. And if you don't want the position reset after failure to 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 goes down with s/regex/replacement/modifiers. The replacement is a Perl double-quoted string that replaces in the string whatever is matched with 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 $_ =~. If there's a match, s/// returns the number of substitutions made; otherwise it returns false. 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, the matched variables $1, $2, etc. are immediately available for 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 returns the result of the substitution 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 gets substituted 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"

And that last one proves s/// can use other delimiters too β€” like s!!! and s{}{}, and even s{}//. If single quotes are used, s''', then the regex and replacement are treated as single-quoted strings.


πŸ¦‹ The split operator πŸ¦‹

split /regex/, string splits string into a list of substrings and returns that list. The regex determines the character sequence that string is split with respect to. To split a string into words, you'd do:

$x = "Calvin and Hobbes";
@word = split /\s+/, $x;  # $word[0] = 'Calvin'
                          # $word[1] = 'and'
                          # $word[2] = 'Hobbes'

To extract a comma-delimited list of numbers:

$x = "1.618,2.718,   3.142";
@const = split /,\s*/, $x;  # $const[0] = '1.618'
                            # $const[1] = '2.718'
                            # $const[2] = '3.142'

If the empty regex // is used, the string is split into individual characters. And if the regex has groupings, then the list produced contains the matched substrings from the groupings as well:

$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. Wild, right? 😭


🧚 use re 'strict' 🧚

New in v5.22, this applies stricter rules than otherwise when compiling regular expression patterns. It can find things that, while legal, may not be what you intended.

See 'strict' in re.


πŸ’€ BUGS πŸ’€

None.

Not a single one. The audacity. The main character energy. Periodt. πŸ‘‘

πŸ”₯ 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.


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 the whole vibe check, bestie 🫢 this page is from perl v5.42.3, dated 2026-08-03, and it lives in the PERLREQUICK(1) section of the manual. Go write some regexes, you absolute icon πŸ’…βœ¨

πŸ“¦ where this page comes from