Regular Expressions: Basic Character Classes
Welcome to the Basic Character Classes lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Some sets of characters occur together frequently. For example, we often need to recognize numbers (the digits 0-9). We can use
\dfor that. It recognizes 0, 1, ..., 8, 9.We use
\sto recognize whitespace: spaces, newlines (\n), tabs (\t), etc.There are more of these, but we'll start with
\sand\d. These are called character classes.>
/\s/.test(' ');Result:
true
>
/\s/.test('\n');Result:
true
>
/\s/.test('');Result:
false
>
/\s/.test('x\ty'); /* \t is a tab character */Result:
true
>
/\s/.test('cat');Result:
false
>
/\d/.test('0');Result:
true
>
/\d/.test('9');Result:
true
>
/\d/.test('a');Result:
false
Making these character classes upper-case negates them. For example,
\dis all digits. But\Dis any character that isn't a digit.>
/\D/.test('0');Result:
false
>
/\S/.test(' ');Result:
false
>
/\S/.test('0');Result:
true
A character class matches only one character in the string. If we want to match multiple characters, we can use
+or*.>
/^\d$/.test('1000');Result:
false
>
/^\d*$/.test('3000');Result:
true
>
/^\d*$/.test('1000 cats');Result:
false
>
/^\d*$/.test('cats');Result:
false
>
/^\d*$/.test('');Result:
true