CodesJava

Easy learning with example program codes

Java regular expression metacharacters


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

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.codesjava;
 
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


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap