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
{}[]()^$.|*+?\
To specifywhere 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:
- "housekeeper" =~ /keeper/; # matches
- "housekeeper" =~ /^keeper/; # doesn't match
- "housekeeper" =~ /keeper$/; # matches
- "housekeeper\n" =~ /keeper$/; # matches
- "housekeeper" =~ /^housekeeper$/; # matches
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 examples:
- /cat/; # matches 'cat'
- /[bcr]at/; # matches 'bat', 'cat', or 'rat'
- "abc" =~ /[cab]/; # matches 'a'
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', 'Yes', 'YES', etc.
- /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 -]\^$
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 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
- /[^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
-
\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"
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 the second regex, cat
is able to match earlier in the string.
- "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 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(cat|keeper)
means match house
followed by either cat
orkeeper
. 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
PS:[] 与 () 的区别,前者只能命中单个字符,后者无此限制
Matching repetitions
The quantifier metacharacters ?
, *
, +
, and {}
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:
-
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 leastn
times, but not more thanm
times. -
a{n,}
= match at leastn
or more times -
a{n}
= match exactlyn
times
Here are some examples:
- /[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