Predefined Character Classes
This is shorthand of Character Classes. Instead of mentioning the character range, we will mention the predefined type of the character.
Construct | Description |
. | Any character (may or may not match line terminators) |
\d | A digit: [0-9] |
\D | A non-digit: [^0-9] |
\s | A whitespace character: [ \t\n\x0B\f\r] |
\S | A non-whitespace character: [^\s] |
\w | A word character: [a-zA-Z_0-9] |
\W | A non-word character: [^\w] |
Above tables shows purpose of each constructs. I believe the description column is enough to understand the function of each construct. So, let’s jump on to the experiment results for each cases,
Note: Constructs beginning with a backslash are called escaped constructs. We have already seen that the use of backslash and \Q
and \E
for quotation. If you are using an escaped construct within a string literal, you must precede the backslash with another backslash for the string to compile. For example
String regExp = "\\d";
Examples
Input String: Tech.Bruiser6738
Regular Expression: .
Replacement String: *
Output String: ****************
Input String: Tech.Bruiser6738
Regular Expression: \d
Replacement String: *
Output String: Tech.Bruiser****
Input String: Tech.Bruiser6738
Regular Expression: \D
Replacement String: *
Output String: ************6738
Input String: Tech.Bruiser 6738
Regular Expression: \s
Replacement String: *
Output String: Tech.Bruiser*6738
Input String: Tech.Bruiser 6738
Regular Expression: \S
Replacement String: *
Output String: ************ ****
Input String: Tech.Bruiser 6738
Regular Expression: \w
Replacement String: *
Output String: ****.******* ****
Input String: Tech.Bruiser 6738
Regular Expression: \W
Replacement String: *
Output String: Tech*Bruiser*6738