Java REGEX – Regular Expression Character Classes


Development environment

  1. JDK 1.8 Downloads
  2. Eclipse Mars Download

In this example we will walk through the character classes below:

Technique Construct Description
Simple Class [abc] a, b, or c
Negation [^abc] Any character except a, b, or c
Range [a-zA-Z] a through z, or A through Z, inclusive
Union [a-d[m-p]] a through d, or m through p: [a-dm-p]
Intersection [a-z&&[def]] d, e, or f
Subtraction [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]

Note: The word “class” in the phrase “character class” does not refer to a .class file. In the context of regular expressions, a character class is a set of characters enclosed within square brackets. It specifies the characters that will successfully match a single character from a given input string.

Step 1 Create Java Project

Launch Eclipse IDE; Create new Java Project by going to File -> New -> Others… -> Java Project. Choose any project name you want then click Finish.

Step 2 Create Java Class

Copy the code below to clipboard; Select src folder in your project; Press CTRL + V; Eclipse IDE will automatically create package & class file with the code that’s pasted from clipboard.

Step 3 Run The Application

Right click to the class; select Run As -> Java Application.