Java Regular Expressions – 4

Predefined Character Classes

This is shorthand of Character Classes. Instead of mentioning the character range, we will mention the predefined type of the character.

ConstructDescription
.Any character (may or may not match line terminators)
\dA digit: [0-9]
\DA non-digit: [^0-9]
\sA whitespace character: [ \t\n\x0B\f\r]
\SA non-whitespace character: [^\s]
\wA word character: [a-zA-Z_0-9]
\WA 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