- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

13.3.2 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 syntactically 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 literally. 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 could be considered part of a range.

Examples:

[a-z]       #  Matches a character that is a lower case ASCII letter.
[a-fz]      #  Matches any letter between 'a' and 'f' (inclusive) or
            #  the letter 'z'.
[-z]        #  Matches either a hyphen ('-') or the letter 'z'.
[a-f-m]     #  Matches any letter between 'a' and 'f' (inclusive), the
            #  hyphen ('-'), or the letter 'm'.
['-?]       #  Matches any of the characters  '()*+,-./0123456789:;<=>?
            #  (But not on an EBCDIC platform).
ISBN 9781906966027Perl Language Reference ManualSee the print edition