Building Simple Character Classes
The most basic type of character class is a set of characters placed side-by-side within square
brackets "[]". For example, the regular expression [bcr]at
, matches the
words "bat", "cat", or "rat" because it uses a character class (that includes
"b","c", or "r") as its first character. Character classes only match singular
characters unless a quantifier is placed after the closing bracket. For examples using
quantifiers with character classes, see Compound Character Classes. The
following table shows how to use simple character classes in regex searches.
[a-d]
is a
range of letters denoting the continuious sequence of a,b,c and d. When a hyphen is otherwise
used in a regex, it matches a literal hyphen.Using simple character classes to perform regex searches.
Example 1: Use a character class to match all cases of the letter "s".
- Regex:
Java[Ss]cript
- Matches:
JavaScript Javascript
- Doesn't Match:
javascript javaScript
Example 2: Use a character class to limit the scope of alternative matches on the words gray and grey.
- Regex:
gr[ae]y
- Matches:
gray grey
- Doesn't Match:
gry graey
Example 3: Use a character class to match any one digit in the list.
- Regex:
[0123456789]
- Matches:
5 0 9
- Doesn't Match:
x ? F
Example 4: To simplify the previous example, use a hyphen "-" within a character class to denote a range for matching any one digit in the list.
- Regex:
[0-9]
- Matches:
5 0 9
- Doesn't Match:
234 42
Example 5: Use a hyphen "-" within a character class to denote an alphabetic range for matching various words ending in "mail".
- Regex:
[A-Z]mail
- Matches:
Email Xmail Zmail
- Doesn't Match:
email mail
Example 6: Match any three or more digits listed in the character class.
- Regex:
[0-9]{3,}
- Matches:
012 1234 555 98754378623
- Doesn't Match:
10 7