In regex, you also have a number of predefined character classes that provide you with a shorthand notation for commonly used sets of characters.
Here are the list:
Predefined Class | Matches |
---|---|
. |
Any character |
d |
Any digit, shorthand for [0-9] |
D |
A non digit, [^0-9] |
s |
A whitespace character [^s] |
S |
Any non whitespace character |
w |
Word character [a-zA-Z_0-9] |
W |
A non word character |
package org.kodejava.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PredefinedCharacterClassDemo {
public static void main(String[] args) {
// Define regex that will search a whitespace followed by f
// and two any characters.
String regex = "\\sf..";
// Compiles the pattern and obtains the matcher object.
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(
"The quick brown fox jumps over the lazy dog");
// find every match and print it
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(), matcher.end());
}
}
}
This program output the following result:
Text " fox" found at 15 to 19.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024