Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Tools

perlrecharclass

Perl 5 version 8.9 documentation
Recently read

perlrecharclass

NAME

perlrecharclass - Perl Regular Expression Character Classes

DESCRIPTION

The top level documentation about Perl regular expressions is found in perlre.

This manual page discusses the syntax and use of character classes in Perl Regular Expressions.

A character class is a way of denoting a set of characters, in such a way that one character of the set is matched. It's important to remember that matching a character class consumes exactly one character in the source string. (The source string is the string the regular expression is matched against.)

There are three types of character classes in Perl regular expressions: the dot, backslashed sequences, and the bracketed form.

The dot

The dot (or period), . is probably the most used, and certainly the most well-known character class. By default, a dot matches any character, except for the newline. The default can be changed to add matching the newline with the single line modifier: either for the entire regular expression using the /s modifier, or locally using (?s).

Here are some examples:

  1. "a" =~ /./ # Match
  2. "." =~ /./ # Match
  3. "" =~ /./ # No match (dot has to match a character)
  4. "\n" =~ /./ # No match (dot does not match a newline)
  5. "\n" =~ /./s # Match (global 'single line' modifier)
  6. "\n" =~ /(?s:.)/ # Match (local 'single line' modifier)
  7. "ab" =~ /^.$/ # No match (dot matches one character)

Backslashed sequences

Perl regular expressions contain many backslashed sequences that constitute a character class. That is, they will match a single character, if that character belongs to a specific set of characters (defined by the sequence). A backslashed sequence is a sequence of characters starting with a backslash. Not all backslashed sequences are character class; for a full list, see perlrebackslash.

Here's a list of the backslashed sequences, which are discussed in more detail below.

  1. \d Match a digit character.
  2. \D Match a non-digit character.
  3. \w Match a "word" character.
  4. \W Match a non-"word" character.
  5. \s Match a white space character.
  6. \S Match a non-white space character.
  7. \pP, \p{Prop} Match a character matching a Unicode property.
  8. \PP, \P{Prop} Match a character that doesn't match a Unicode property.

Digits

\d matches a single character that is considered to be a digit. What is considered a digit depends on the internal encoding of the source string. If the source string is in UTF-8 format, \d not only matches the digits '0' - '9', but also Arabic, Devanagari and digits from other languages. Otherwise, if there is a locale in effect, it will match whatever characters the locale considers digits. Without a locale, \d matches the digits '0' to '9'. See Locale, Unicode and UTF-8.

Any character that isn't matched by \d will be matched by \D .

Word characters

\w matches a single word character: an alphanumeric character (that is, an alphabetic character, or a digit), or the underscore (_ ). What is considered a word character depends on the internal encoding of the string. If it's in UTF-8 format, \w matches those characters that are considered word characters in the Unicode database. That is, it not only matches ASCII letters, but also Thai letters, Greek letters, etc. If the source string isn't in UTF-8 format, \w matches those characters that are considered word characters by the current locale. Without a locale in effect, \w matches the ASCII letters, digits and the underscore.

Any character that isn't matched by \w will be matched by \W .

White space

\s matches any single character that is consider white space. In the ASCII range, \s matches the horizontal tab (\t ), the new line (\n ), the form feed (\f ), the carriage return (\r ), and the space (the vertical tab, \cK is not matched by \s). The exact set of characters matched by \s depends on whether the source string is in UTF-8 format. If it is, \s matches what is considered white space in the Unicode database. Otherwise, if there is a locale in effect, \s matches whatever is considered white space by the current locale. Without a locale, \s matches the five characters mentioned in the beginning of this paragraph. Perhaps the most notable difference is that \s matches a non-breaking space only if the non-breaking space is in a UTF-8 encoded string.

It is worth noting that \d , \w , etc, match single characters, not complete numbers or words. To match a number (that consists of integers), use \d+ ; to match a word, use \w+ .

Unicode Properties

\pP and \p{Prop} are character classes to match characters that fit given Unicode classes. One letter classes can be used in the \pP form, with the class name following the \p , otherwise, the property name is enclosed in braces, and follows the \p . For instance, a match for a number can be written as /\pN/ or as /\p{Number}/ . Lowercase letters are matched by the property LowercaseLetter which has as short form Ll. They have to be written as /\p{Ll}/ or /\p{LowercaseLetter}/ . /\pLl/ is valid, but means something different. It matches a two character string: a letter (Unicode property \pL ), followed by a lowercase l .

For a list of possible properties, see Unicode Character Properties in perlunicode. It is also possible to defined your own properties. This is discussed in User-Defined Character Properties in perlunicode.

Examples

  1. "a" =~ /\w/ # Match, "a" is a 'word' character.
  2. "7" =~ /\w/ # Match, "7" is a 'word' character as well.
  3. "a" =~ /\d/ # No match, "a" isn't a digit.
  4. "7" =~ /\d/ # Match, "7" is a digit.
  5. " " =~ /\s/ # Match, a space is white space.
  6. "a" =~ /\D/ # Match, "a" is a non-digit.
  7. "7" =~ /\D/ # No match, "7" is not a non-digit.
  8. " " =~ /\S/ # No match, a space is not non-white space.
  9. "a" =~ /\pL/ # Match, "a" is a letter.
  10. "a" =~ /\p{Lu}/ # No match, /\p{Lu}/ matches upper case letters.
  11. "\x{0e0b}" =~ /\p{Thai}/ # Match, \x{0e0b} is the character
  12. # 'THAI CHARACTER SO SO', and that's in
  13. # Thai Unicode class.
  14. "a" =~ /\P{Lao}/ # Match, as "a" is not a Laoian character.

Bracketed Character Classes

The third form of character class you can use in Perl regular expressions is the bracketed form. In its simplest form, it lists the characters that may be matched inside square brackets, like this: [aeiou] . This matches one of a , e , i , o or u . Just as the other character classes, exactly one character will be matched. To match a longer string consisting of characters mentioned in the characters class, follow the character class with a quantifier. For instance, [aeiou]+ matches a string of one or more lowercase ASCII vowels.

Repeating a character in a character class has no effect; it's considered to be in the set only once.

Examples:

  1. "e" =~ /[aeiou]/ # Match, as "e" is listed in the class.
  2. "p" =~ /[aeiou]/ # No match, "p" is not listed in the class.
  3. "ae" =~ /^[aeiou]$/ # No match, a character class only matches
  4. # a single character.
  5. "ae" =~ /^[aeiou]+$/ # Match, due to the quantifier.

Special Characters Inside a Bracketed Character Class

Most characters that are meta characters in regular expressions (that is, characters that carry a special meaning like * or () lose their special meaning and can be used inside a character class without the need to escape them. For instance, [()] matches either an opening parenthesis, or a closing parenthesis, and the parens inside the character class don't group or capture.

Characters that may carry a special meaning inside a character class are: \ , ^, - , [ and ], and are discussed below. They can be escaped with a backslash, although this is sometimes not needed, in which case the backslash may be omitted.

The sequence \b is special inside a bracketed character class. While outside the character class \b is an assertion indicating a point that does not have either two word characters or two non-word characters on either side, inside a bracketed character class, \b matches a backspace character.

A [ is not special inside a character class, unless it's the start of a POSIX character class (see below). It normally does not need escaping.

A ] is either the end of a POSIX character class (see below), or it signals the end of the bracketed character class. Normally it needs escaping if you want to include a ] in the set of characters. However, if the ] is the first (or the second if the first character is a caret) character of a bracketed character class, it does not denote the end of the class (as you cannot have an empty class) and is considered part of the set of characters that can be matched without escaping.

Examples:

  1. "+" =~ /[+?*]/ # Match, "+" in a character class is not special.
  2. "\cH" =~ /[\b]/ # Match, \b inside in a character class
  3. # is equivalent with a backspace.
  4. "]" =~ /[][]/ # Match, as the character class contains.
  5. # both [ and ].
  6. "[]" =~ /[[]]/ # Match, the pattern contains a character class
  7. # containing just ], and the character class is
  8. # followed by a ].

Character Ranges

It is not uncommon to want to match a range of characters. Luckily, instead of listing all the characters in the range, one may use the hyphen (- ). If inside a bracketed character class you have two characters separated by a hyphen, it's treated as if all the characters between the two are in the class. For instance, [0-9] matches any ASCII digit, and [a-m] matches any lowercase letter from the first half of the ASCII alphabet.

Note that the two characters on either side of the hyphen are not necessary both letters or both digits. Any character is possible, although not advisable. ['-?] contains a range of characters, but most people will not know which characters that will be. Furthermore, such ranges may lead to portability problems if the code has to run on a platform that uses a different character set, such as EBCDIC.

If a hyphen in a character class cannot be part of a range, for instance because it is the first or the last character of the character class, or if it immediately follows a range, the hyphen isn't special, and will be considered a character that may be matched. You have to escape the hyphen with a backslash if you want to have a hyphen in your set of characters to be matched, and its position in the class is such that it can be considered part of a range.

Examples:

  1. [a-z] # Matches a character that is a lower case ASCII letter.
  2. [a-fz] # Matches any letter between 'a' and 'f' (inclusive) or the
  3. # letter 'z'.
  4. [-z] # Matches either a hyphen ('-') or the letter 'z'.
  5. [a-f-m] # Matches any letter between 'a' and 'f' (inclusive), the
  6. # hyphen ('-'), or the letter 'm'.
  7. ['-?] # Matches any of the characters '()*+,-./0123456789:;<=>?
  8. # (But not on an EBCDIC platform).

Negation

It is also possible to instead list the characters you do not want to match. You can do so by using a caret (^) as the first character in the character class. For instance, [^a-z] matches a character that is not a lowercase ASCII letter.

This syntax make the caret a special character inside a bracketed character class, but only if it is the first character of the class. So if you want to have the caret as one of the characters you want to match, you either have to escape the caret, or not list it first.

Examples:

  1. "e" =~ /[^aeiou]/ # No match, the 'e' is listed.
  2. "x" =~ /[^aeiou]/ # Match, as 'x' isn't a lowercase vowel.
  3. "^" =~ /[^^]/ # No match, matches anything that isn't a caret.
  4. "^" =~ /[x^]/ # Match, caret is not special here.

Backslash Sequences

You can put a backslash sequence character class inside a bracketed character class, and it will act just as if you put all the characters matched by the backslash sequence inside the character class. For instance, [a-f\d] will match any digit, or any of the lowercase letters between 'a' and 'f' inclusive.

Examples:

  1. /[\p{Thai}\d]/ # Matches a character that is either a Thai
  2. # character, or a digit.
  3. /[^\p{Arabic}()]/ # Matches a character that is neither an Arabic
  4. # character, nor a parenthesis.

Backslash sequence character classes cannot form one of the endpoints of a range.

Posix Character Classes

Posix character classes have the form [:class:], where class is name, and the [: and :] delimiters. Posix character classes appear inside bracketed character classes, and are a convenient and descriptive way of listing a group of characters. Be careful about the syntax,

  1. # Correct:
  2. $string =~ /[[:alpha:]]/
  3. # Incorrect (will warn):
  4. $string =~ /[:alpha:]/

The latter pattern would be a character class consisting of a colon, and the letters a , l , p and h .

Perl recognizes the following POSIX character classes:

  1. alpha Any alphabetical character.
  2. alnum Any alphanumerical character.
  3. ascii Any ASCII character.
  4. blank A GNU extension, equal to a space or a horizontal tab (C<\t>).
  5. cntrl Any control character.
  6. digit Any digit, equivalent to C<\d>.
  7. graph Any printable character, excluding a space.
  8. lower Any lowercase character.
  9. print Any printable character, including a space.
  10. punct Any punctuation character.
  11. space Any white space character. C<\s> plus the vertical tab (C<\cK>).
  12. upper Any uppercase character.
  13. word Any "word" character, equivalent to C<\w>.
  14. xdigit Any hexadecimal digit, '0' - '9', 'a' - 'f', 'A' - 'F'.

The exact set of characters matched depends on whether the source string is internally in UTF-8 format or not. See Locale, Unicode and UTF-8.

Most POSIX character classes have \p counterparts. The difference is that the \p classes will always match according to the Unicode properties, regardless whether the string is in UTF-8 format or not.

The following table shows the relation between POSIX character classes and the Unicode properties:

  1. [[:...:]] \p{...} backslash
  2. alpha IsAlpha
  3. alnum IsAlnum
  4. ascii IsASCII
  5. blank
  6. cntrl IsCntrl
  7. digit IsDigit \d
  8. graph IsGraph
  9. lower IsLower
  10. print IsPrint
  11. punct IsPunct
  12. space IsSpace
  13. IsSpacePerl \s
  14. upper IsUpper
  15. word IsWord
  16. xdigit IsXDigit

Some character classes may have a non-obvious name:

  • cntrl

    Any control character. Usually, control characters don't produce output as such, but instead control the terminal somehow: for example newline and backspace are control characters. All characters with ord() less than 32 are usually classified as control characters (in ASCII, the ISO Latin character sets, and Unicode), as is the character ord() value of 127 (DEL ).

  • graph

    Any character that is graphical, that is, visible. This class consists of all the alphanumerical characters and all punctuation characters.

  • print

    All printable characters, which is the set of all the graphical characters plus the space.

  • punct

    Any punctuation (special) character.

Negation

A Perl extension to the POSIX character class is the ability to negate it. This is done by prefixing the class name with a caret (^). Some examples:

  1. POSIX Unicode Backslash
  2. [[:^digit:]] \P{IsDigit} \D
  3. [[:^space:]] \P{IsSpace} \S
  4. [[:^word:]] \P{IsWord} \W

[= =] and [. .]

Perl will recognize the POSIX character classes [=class=] , and [.class.], but does not (yet?) support this construct. Use of such a constructs will lead to an error.

Examples

  1. /[[:digit:]]/ # Matches a character that is a digit.
  2. /[01[:lower:]]/ # Matches a character that is either a
  3. # lowercase letter, or '0' or '1'.
  4. /[[:digit:][:^xdigit:]]/ # Matches a character that can be anything,
  5. # but the letters 'a' to 'f' in either case.
  6. # This is because the character class contains
  7. # all digits, and anything that isn't a
  8. # hex digit, resulting in a class containing
  9. # all characters, but the letters 'a' to 'f'
  10. # and 'A' to 'F'.

Locale, Unicode and UTF-8

Some of the character classes have a somewhat different behaviour depending on the internal encoding of the source string, and the locale that is in effect.

\w , \d , \s and the POSIX character classes (and their negations, including \W , \D , \S ) suffer from this behaviour.

The rule is that if the source string is in UTF-8 format, the character classes match according to the Unicode properties. If the source string isn't, then the character classes match according to whatever locale is in effect. If there is no locale, they match the ASCII defaults (52 letters, 10 digits and underscore for \w , 0 to 9 for \d , etc).

This usually means that if you are matching against characters whose ord() values are between 128 and 255 inclusive, your character class may match or not depending on the current locale, and whether the source string is in UTF-8 format. The string will be in UTF-8 format if it contains characters whose ord() value exceeds 255. But a string may be in UTF-8 format without it having such characters.

For portability reasons, it may be better to not use \w , \d , \s or the POSIX character classes, and use the Unicode properties instead.

Examples

  1. $str = "\xDF"; # $str is not in UTF-8 format.
  2. $str =~ /^\w/; # No match, as $str isn't in UTF-8 format.
  3. $str .= "\x{0e0b}"; # Now $str is in UTF-8 format.
  4. $str =~ /^\w/; # Match! $str is now in UTF-8 format.
  5. chop $str;
  6. $str =~ /^\w/; # Still a match! $str remains in UTF-8 format.