Java regular expression metacharacters

Java regex metacharacters

Regex Description
. Any character (may or may not match terminator)
d Any digits, short of [0-9]
D Any non-digit, short for [^0-9]
s Any whitespace character, short for [tnx0Bfr]
S Any non-whitespace character, short for [^s]
w Any word character, short for [a-zA-Z_0-9]
W Any non-word character, short for [^w]
b A word boundary
B A non-word boundary

Regex Character Class Example

package com.w3schools;
 
import java.util.regex.Pattern;
 
public class RegexTest {
	public static void main(String args[]){
		//\d means digit
		System.out.println("metacharacters d....");  
 
		//false (non-digit)  
		System.out.println(Pattern.matches("\d", "jai"));
		//true (digit and comes once)
		System.out.println(Pattern.matches("\d", "5"));  
		//false (digit but comes more than once)  
		System.out.println(Pattern.matches("\d", "3343"));
		//false (digit and char)
		System.out.println(Pattern.matches("\d", "323abc"));  
 
		//\D means non-digit 
		System.out.println("metacharacters D....");  
		//false (non-digit but comes more than once)  
		System.out.println(Pattern.matches("\D", "jai"));
		//false (digit)  
		System.out.println(Pattern.matches("\D", "5"));
		//false (digit) 
		System.out.println(Pattern.matches("\D", "3343")); 
		//false (digit and char)  
		System.out.println(Pattern.matches("\D", "323abc"));
		//true (non-digit and comes once)
		System.out.println(Pattern.matches("\D", "j"));  
 
		System.out.println("metacharacters D with quantifier....");  
		//true (non-digit and may come 0 or more times)
		System.out.println(Pattern.matches("\D*", "jai")); 
	}
}

Output

true
metacharacters d....
false
true
false
false
metacharacters D....
false
false
false
false
true
metacharacters D with quantifier....
true