Character class means digits, letters, and whitespace characters.
The special characters are displayed in the following table:
Character Characters Class | It Matches | Example |
---|---|---|
\d | Any digit from 0 to 9 | \d\d matches 72, but not aa or 7a. |
\D | Any character that is not a digit | \D\D\D matches abc, but not 123 or 8ef. |
w | Any word character; that is, A-Z, a-z, 0-9, and the underscore character (_) | \w\w\w\w matches Ab_2, but not $% or Ab_@. |
\W | Any non-word character | \W matches @, but not a. |
\s | Any whitespace character | \s matches tab, return, formfeed, and vertical tab. |
\S | Any non-whitespace character | \S matches A, but not the tab character. |
. | Any single character other than the newline character (\n) | . matches a or 4 or @. |
[...] | Any one of the characters between the brackets[a-z] matches any character in the range a to z | [abc] matches a or b or c, but nothing else. |
[^...] | Any one character, but not one of those inside the brackets | [^abc] matches any character except a or b or c. [^a-z] matches any character that is not in the range a to z. |
To match a telephone number in the format 1-800-888-1234, the regular expression would be as follows:
\d-\d\d\d-\d\d\d-\d\d\d\d
The following code checks that a pass phrase contains only letters and numbers-that is, alphanumeric characters, not punctuation or symbols like @, %, and so on:
let input = "this is a test"; function isValid (text) { let myRegExp = /[^a-z\d ]/i; return !(myRegExp.test(text)); } if (isValid(input)) { console.log("Your text contains only valid characters"); } else { //from w ww . j ava 2 s.c o m console.log("Your text contains one or more invalid characters"); }
Let's see how this translates into a regular expression:
1.You use square brackets with the ^ symbol:
[^]
This means you want to match any character that is not one of the characters specified inside the square brackets.
2. You add a-z, which specifies any character in the range a through z:
[^a-z]
So far, your regular expression matches any character that is not between a and z.
Because you added the i to the end of the expression definition, you've made the pattern case-insensitive.
So your regular expression actually matches any character not between A and Z or a and z.
3.You add \d to indicate any digit character, or any character between 0 and 9:
[^a-z\d]
4.Your expression matches any character that is not between a and z, A and Z, or 0 and 9.
You decide that a space is valid, so you add that inside the square brackets:
[^a-z\d ]
Putting this all together, you have a regular expression that matches any character that is not a letter, a digit, or a space.