Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Character Classes in java regular expression

We use character classes to search a group of things. The following represents the Character Classes.


Character Classes supported by Java:

[abc] - we are searching for either 'a' or 'b' or 'c'.
[^ abc] - Except 'a','b' and 'c'.
[a-z] - any lower case alphabet symbol
[A-Z] - any upper case alphabet symbol
[a-z A-Z] - any alphabet symbol
[0-9] - Any digit from 0-9
[a-z A-Z 0-9]- Any alphanumeric character
[^a-z A-Z 0-9] - Except alphanumeric characters(Special Characters)

Let's see a demo program by using character classes:

Class RegexDemo3 {
	public static void main(String[] args) {
		Pattern p = Pattern.compile("x");
		Matcher m = p.matcher("a7b@Z#9");
		while (m.find()) {
			System.out.println(m.start() + "....." + m.end());
		}
	}
}

Output

X=[abc] X=[^abc] X=[a-z] X=[0-9] X=[a-z A-Z 0-9] X=[^a-z A-Z 0-9]

0.....a

2.....b

1.....7

3.....@

4.....Z

5.....#

6.....9

0.....a

2.....b

4.....Z

1.....7

6.....9

0.....a

1.....7

2.....b

4.....Z

6.....9

3.....@

5.....#

 

Pre-defined character classes:

\s: space character
\S: Except space character, any character
\d: Any digit from 0 to 9
\D: Except digits any character
\w:Any word character[a-z A-Z 0-9]
\W: Except word character i.e. special character
. : Any symbol including special character also

Let's see a demo program by using pre-defined character classes:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegExDemo2 {
	public static void main(String[] args) {
		Pattern p = Pattern.compile("\\s");
		Matcher m = p.matcher("a7bk@9");
		while (m.find()) {
			System.out.println(m.start() + "..." + m.group());
		}
	}
}

Output

X=\\s X=\\d X=\\0 X=\\w X=\\W

0...a

2....b

4...k

5...@

6...9

1...7

6...9

0...a

2...b

3...

4...k

5...@

0...a

1...7

2...b

4...k

6...9

3...

5...@

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext