Regular Expressions: Character Sets
Welcome to the Character Sets lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
In a character set, characters and ranges can be mixed in any order. This regex is equivalent to
/[g]|[c-e]|[a]/.>
/[gc-ea]/.test('a');Result:
true
>
/[gc-ea]/.test('b');Result:
false
>
/[gc-ea]/.test('c');Result:
true
>
/[gc-ea]/.test('d');Result:
true
>
/[gc-ea]/.test('h');Result:
false
We can also negate the whole character set, even if it's complex.
>
/[^gc-ea]/.test('a');Result:
false
>
/[^gc-ea]/.test('d');Result:
false
>
/[^gc-ea]/.test('b');Result:
true
If a character set ever gives you trouble, you can always break it up. For example,
/[hbd-fa]/can be thought of as/(h|b|[d-f]|a)/. This trick works for anything in regexes. Most regex features are syntactic sugar for simple features like|.Special characters aren't special inside a character set. For example, "." means a literal "." and "$" is a literal "$".
>
/[a$]/.test('$');Result:
true
>
/[a$]/.test('a');Result:
true
>
/[a$]/.test('^');Result:
false
>
/^[a$]$/.test('ab');Result:
false
The
^is only special if it's the first character in the set. There, it means "negate this set". But a^anywhere else in the set is just another literal character.>
/[^b]/.test('b');Result:
false
>
/[b^]/.test('b');Result:
true
>
/[b^]/.test('^');Result:
true
>
/[^^]/.test('b');Result:
true
>
/[^^]/.test('^');Result:
false