PERLREQUICK
NAME DESCRIPTION The Guide BUGS SEE ALSO AUTHOR AND COPYRIGHT
perlrequick - Perl regular expressions quick start
This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl.
Simple word matching
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:
In this statement, World is a regex and the // enclosing /World/ tells perl to search a string for a match. The operator = 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, World matches the second word in , so the expression is true. This idea has several variations.
Expressions like this are useful in
Finally, the // default delimiters for a match can be changed to arbitrary delimiters by putting an 'm' out front:
Regexes must match a part of the string exactly in order for the statement to be true:
perl will always match at the earliest possible point in the string:
Not all characters can be used 'as is' in a match. Some characters, called metacharacters, are reserved for use in regex notation. The metacharacters are
{}[()^$.*+?\
A metacharacter can be matched by putting a backslash before it:
In the last regex, the forward slash '/' is also backslashed, because it is used to delimit the regex.
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:
'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. To specify where it should match, we would 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:
Using character classes
A character class 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 [..., with the set of characters to be possibly matched inside. Here are some
/[bcrat/; # matches 'bat', 'cat', or 'rat' In the 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/i; # also match 'yes' in a case-insensitive way The last example shows a match with an 'i' modifier, which makes the match case-insensitive.
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
$x = 'bcr'; /[$xat/; # matches 'bat, 'cat', or 'rat' /[$xat/; # matches '$at' or 'xat' /[\$xat/; # matches 'at', 'bat, 'cat', or 'rat'
/[0-9a-fA-F/; # matches a hexadecimal digit If '-' is the first or last character in a character class, it is 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. Then
/[^aat/; # doesn't match 'aat' or 'at', but matches
/[^0-9/; # matches a non-numeric character /[a^at/; # matches 'aat' or '^at'; here '^' is ordinary Perl has several abbreviations for common character classes:
d is a digit and represents [0-9
s is a whitespace character and represents [unrenderable node]
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 dswDSW abbreviations can be used both inside and outside of character classes. Here are some in
/[ds/; # matches any digit or whitespace character /wWw/; # matches a word char, followed by a
/..rt/; # matches any two chars, followed by 'rt' /end./; # matches 'end.' /end[./; # same thing, matches 'end.'
In the last example, the end of the string is considered a word boundary.
Matching this or that
We can match match different character strings with the alternation metacharacter ''. To match dog or cat, we form the regex dogcat. 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 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:
Even though dog is the first alternative in the second regex, cat is able to match earlier in the string.
At a given character position, the first alternative that allows the regex match to succeed wil be the one that matches. Here, all the alternatives match at the first string position, so th first matches.
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(catkeeper) means match house followed by either cat or keeper. Some more examples are
/(ab)b/; # matches 'ab' or 'bb'
/(^ab)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
Extracting matches
The grouping metacharacters () 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 $1, $2, etc. They can be used
$time = /(dd):(dd):(dd)/; # match hh:mm:ss format $hours = $1; $minutes = $2; $seconds = $3; In list context, a match /regex/ with groupings will return the list of matched values ($1,$2,...). So we could rewrite it as
($hours, $minutes, $second) = ($time = /(dd):(dd):(dd)/);
1 2 34
$1, $2, ... should only be used outside of a regex, and 1, 2, ... only inside a regex.
Matching repetitions
The quantifier metacharacters ?, *,
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:
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 exactly n times
/(w+)s+1/; # match doubled words of arbitrary length $year = /d{2,4}/; # make sure year is at least 2 but not more
$year = /d{4}d{2}/; # better match; throw out 3 digit dates These quantifiers will try to match as much of the string as possible, while still allowing the regex to match. So we have
$x = 'the cat in the hat';
$x = /^(.*)(at)(.*)$/; # matches,
The first quantifier .* grabs as much of the string as possible while still having the regex match. The second quantifier .* has no string left to it, so it matches 0 times.
More matching
There are a few more things you might want to know about matching operators. In the code
$pattern = 'Seuss';
while (
m'$pattern'; # matches '$pattern', not 'Seuss' The global modifier //g allows the matching operator to 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 the position with the pos() function. For example,
$x =
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. 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,
Search and replace
Search and replace is performed using 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 = is also used here to associate a string with s///. If matching against $_, the $_ = can be dropped. If there is a match, s/// returns the number of substitutions made, otherwise it returns false. Here are a
$x =
$x = The last example shows that s/// can use other delimiters, such as 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. For example, to split a string into words, use
$x =
To extract a comma-delimited list of numbers, use
$x =
Since the first character of $x matched the regex, split prepended an empty initial element to the list.
None.
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.
One page links to perlrequick(1):