Java examples on Java Regex
- How do I split-up string using regular expression?
- How do I create a string search and replace using regex?
- How do I do regular expression in Java?
- How do I check if a string starts with a pattern?
- How do I determine if a string match a pattern exactly?
- How do I use logical OR operator in regex?
- How do I find and replace string?
- How do I write embedded flag expression?
- How do I do boundary matching in regex?
- How do I use capturing groups in regex?
- How do I match a regex pattern in case insensitive?
- How do I count the number of capturing groups?
- How do I use quantifier in regex?
- How do I write simple character class regex?
- How do I write character class subtraction regex?
- How do I write negated character class regex?
- How do I use possessive quantifier regex?
- How do I write union character class regex?
- How do I write range character class regex?
- How do I use predefined character classes regex?
- How do I use reluctant quantifier regex?
- How do I write character class intersection regex?
- How do I combile character classes with quantifier?
- How to remove non ASCII characters from a string?
- How to truncate a string after n number of words?
How do I use predefined character classes regex?
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:
.: represent any character.\d: represent any digit, shorthand for[0-9]\D: represent a non digit,[^0-9]\s: represent a whitespace character[^\s]\S: represent any non whitespace character\w: represent word character[a-zA-Z_0-9]\W: represent a non word character
package org.kodejava.example.util.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.