Java regular expression metacharacters

Java regex metacharacters

RegexDescription
.Any character (may or may not match terminator)
dAny digits, short of [0-9]
DAny non-digit, short for [^0-9]
sAny whitespace character, short for [tnx0Bfr]
SAny non-whitespace character, short for [^s]
wAny word character, short for [a-zA-Z_0-9]
WAny non-word character, short for [^w]
bA word boundary
BA non-word boundary

Regex Character Class Example

package com.w3spoint;
 
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
Content Protection by DMCA.com
Please Share