Java regular expression character class regex

Java Regex Character classes

Character Class Description
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a-zA-Z] a through z or A through Z, inclusive (range)
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]] d, e, or f (intersection)
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Regex Character Class Example

package com.w3spoint;
 
import java.util.regex.Pattern;
 
public class RegexTest {
	public static void main(String args[]){
		//true (2nd char is j)
		System.out.println(Pattern.matches(".j", "pj"));  
		//false (2nd char is not s)  
		System.out.println(Pattern.matches(".j", "ab"));
		//false (s is not the last char)  
		System.out.println(Pattern.matches(".s", "msa"));
		//false (has more than 2 char before s)  
		System.out.println(Pattern.matches(".s", "pjms"));
		//true (3rd char is s)   
		System.out.println(Pattern.matches("..s", "pjs"));
	}
}

Output

true
false
false
false
true
Please follow and like us:
Content Protection by DMCA.com