4.8. Limit Input to Alphanumeric Characters

Problem

Your application requires that users limit their responses to one or more alphanumeric characters from the English alphabet.

Solution

With regular expressions at your disposal, the solution is dead simple. A character class can set up the allowed range of characters. With an added quantifier that repeats the character class one or more times, and anchors that bind the match to the start and end of the string, you’re good to go.

Regular expression

^[A-Z0-9]+$
Regex options: Case insensitive
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Ruby

if subject =~ /^[A-Z0-9]+$/i
    puts "Subject is alphanumeric"
else
    puts "Subject is not alphanumeric"
end

Other programming languages

See Recipes 3.4 and 3.5 for help implementing this regular expression with other programming languages.

Discussion

Let’s look at the four pieces of this regular expression one at a time:

^         # Assert position at the beginning of the string.
[A-Z0-9]  # Match a character from "A" to "Z" or from "0" to "9"...
  +       #   between one and unlimited times.
$         # Assert position at the end of the string.
Regex options: Case insensitive, free-spacing
Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby

The ^ and $ assertions at the beginning and end of the regular expression ensure that the entire input string is tested. Without them, the regex could match any part of a longer string, letting invalid characters through. The plus quantifier + repeats the preceding element one or more times. If you wanted to allow the regex to match an entirely empty string, you could replace the + with *. The asterisk quantifier * allows zero or more repetitions, effectively making the preceding element optional.

Variations

Limit input to ASCII characters

The following regular expression limits input to the 128 characters in the seven-bit ASCII character table. This includes 33 nonvisible control characters:

^[\x00-\x7F]+$
Regex options: None
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Limit input to ASCII non-control characters and line breaks

Use the following regular expression to limit input to visible characters and whitespace in the ASCII character table, excluding control characters. The line feed and carriage return characters (at positions 0x0A and 0x0D, respectively) are the most commonly used control characters, so they’re explicitly included using \n (line feed) and \r (carriage return):

^[\n\r\x20-\x7E]+$
Regex options: None
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Limit input to shared ISO-8859-1 and Windows-1252 characters

ISO-8859-1 and Windows-1252 (often referred to as ANSI) are two commonly used eight-bit character encodings that are both based on the Latin-1 standard (or more formally, ISO/IEC 8859-1). However, the characters they map to the positions between 0x80 and 0x9F are incompatible. ISO-8859-1 uses these positions for control codes, whereas Windows-1252 uses them for an extended range of letters and punctuation. These differences sometimes lead to difficulty displaying characters, particularly with documents that do not declare their encoding or when the recipient is using a non-Windows system. The following regular expression can be used to limit input to characters that are shared by ISO-8859-1 and Windows-1252 (including shared control characters):

^[\x00-\x7F\xA0-\xFF]+$
Regex options: None
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

The hexadecimal notation might make this regular expression hard to read, but it works the same way as the [A-Z0-9] character class shown earlier. It matches characters in two ranges: \x00-\x7F and \xA0-\xFF.

Limit input to alphanumeric characters in any language

This regular expression limits input to letters and numbers from any language or script. It uses a character class that includes properties for all code points in the Unicode letter and number categories:

^[\p{L}\p{N}]+$
Regex options: None
Regex flavors: .NET, Java, PCRE, Perl, Ruby 1.9

Unfortunately, Unicode properties are not supported by all of the regular expression flavors covered by this book. Specifically, this regex will not work with JavaScript, Python, or Ruby 1.8. Additionally, using this regex with PCRE requires PCRE to be compiled with UTF-8 support. Unicode properties can be used with PHP’s preg functions (which rely on PCRE) if the /u option is appended to the regex.

The following regex shows a workaround for Python:

^[^\W_]+$
Regex options: Unicode
Regex flavors: Python

Here, we work around the lack of Unicode properties in Python by using the UNICODE or U flag when creating the regular expression. This changes the meaning of some regex tokens by making them use the Unicode character table. \w gets us most of the way to a solution since it matches alphanumeric characters and the underscore. By using its inverse (\W) in a negated character class, we can remove the underscore from this set. Double negatives like this are occasionally quite useful in regular expressions, though perhaps a little difficult to wrap your head around.[6]

See Also

Recipe 4.9 shows how to limit text by length instead of character set.



[6] For even more fun (if you have a twisted definition of fun), try creating triple, quadruple, or even greater levels of negatives by throwing in negative lookaround (see Recipe 2.16) and character class subtraction (see Flavor-Specific Features in Recipe 2.3).

Get Regular Expressions Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.