Easy learning with example program codes

Java regular expression character class regex

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



Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at


We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki