19 Jan Java Regular Expressions
To perform search and manipulation on strings in Java, use Regex i.e., Regular Expressions. To form a search pattern, match or find strings, and search and edit strings, we use Regular Expressions as a sequence of characters. To work with regex in Java, import the java.util.regex package:
- Pattern Class
- Matcher Class
Pattern Class
A Pattern class is a compiled representation of a regular expression to define a pattern. For a pattern, call its compile() method to return a Pattern object.
Matcher Class
The Matcher Class performs match operations on a character sequence by interpreting a Pattern. For a Matcher object, call the matcher() method on a Pattern object.
Regex Quantifiers
To define quantities, i.e., the occurrences of a character, Regex in Java has Quantifiers. Here is the list of Quantifiers in Java that match any string containing,

Let us now see an example of Quantifiers in Regular Expressions:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Studyopedia {
public static void main(String args[]){
System.out.println("Quantifier example...");
// Returns true since p or q or r or s appears once
System.out.println(Pattern.matches("[pqrs]?", "p"));
// Returns false since r appears more than one times
System.out.println(Pattern.matches("[pqrs]?", "rrrr"));
// Returns false since p, q, r and s appears more than one times
System.out.println(Pattern.matches("[pqrs]?", "ppqqrrss"));
}
}
Output
Quantifier example... true false false
Regex Metacharacters
The following are the metacharacters in Regular Expressions and finds,

Let us now see an example of Metacharacters in Regular Expressions:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Studyopedia {
public static void main(String args[]){
System.out.println("Metacharacters example...");
// Returns false since it is a non-digit
System.out.println(Pattern.matches("\\d", "pqrst"));
// Returnstrue since it is a digit and appears once
System.out.println(Pattern.matches("\\d", "5"));
// Returns false since it is a digit and appears more than once
System.out.println(Pattern.matches("\\d", "228"));
// Returns false since it is a non-digit and appears more than once
System.out.println(Pattern.matches("\\D", "pqrst"));
}
}
Output
Metacharacters example... false true false false
Above, the metacharacter is \d, but we are using \\d. The reason we write \\d instead of just \d in Java strings come down to how Java handles escape sequences in string literals:
- In regex,
\dis a metacharacter that means “any digit” (0–9). - In Java strings, the backslash
\is itself an escape character (used for things like\nfor newline,\tfor tab). - So if you write
"\d"in Java, the compiler will complain because\dis not a valid escape sequence in Java string syntax. - To represent a literal backslash in a Java string, you must escape it as
"\\". - Therefore, to pass
\dinto the regex engine, you write"\\d"in your Java code.
Let us see some other examples of Regular Expressions in Java.
Regular Expression – Examples
- Example 1: Search for a letter in a word with Regex in Java
- Example 2: Find multiple occurrences (with index) of a letter in a word with Regex
- Example 3: Check if a word contains a letter in Java with Regex
- Example 4: Find all vowels in a word with Regex in Java
- Example 5: Check if a word contains at least one vowel with Regex in Java
- Example 6: Find digits in a word with Regex in Java
- Example 7: Extract all numbers from a sentence with Regex in Java
To write a Regex in Java, we used both the Pattern and Matcher classes. Let us see two examples.
Search for a letter in a word with Regex in Java
In this first example, we will search for a letter in a word with Regular Expressions in Java. If it is found, True gets displayed. The pattern is case-insensitive, set using the Flag Pattern.CASE_INSENSITIVE:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Studyopedia {
public static void main(String args[]){
// Here . means a single character
Pattern pattern = Pattern.compile(".k", Pattern.CASE_INSENSITIVE);
Matcher match = pattern.matcher("tK");
boolean res = match.matches();
System.out.println("Match Found: "+res);
}
}
Output
Match Found: true
We can also write the above example in a more compact form as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Studyopedia {
public static void main(String args[]){
// Here . means a single character
boolean res = Pattern.compile(".k").matcher("tk").matches();
System.out.println("Match Found: "+res);
}
}
Output
Match Found: true
Find multiple occurrences (with index) of a letter in a word with Regex
// Find multiple occurrences (with index) of a letter in a word with RegExp
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo116 {
public static void main(String[] args) {
String word = "banana";
String regex = "a";
// Patter.compile("a") looks for letter "a"
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(word);
// matcher.find() finds each occurrence
// matcher.start() gives the index of the match
while(matcher.find()) {
System.out.println(matcher.start());
}
}
}
Output
1 3 5
Check if a word contains a letter in Java with Regex
// Check if a word contains a letter in Java with RegExp
class Demo117 {
public static void main(String[] args) {
String word = "hello";
if(word.matches(".*e.*")) {
System.out.println("Word contains e");
}
else {
System.out.println("Word not contains e");
}
}
}
Output
Word contains e
Find all vowels in a word with Regex in Java
// Find all vowels in a word with RegExp in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo118 {
public static void main(String[] args) {
String word = "education";
String regex = "[aeiou]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(word);
while(matcher.find()){
System.out.println("Vowel found = "+matcher.group()+" at index = "+matcher.start());
}
}
}
Output
Vowel found = e at index = 0 Vowel found = u at index = 2 Vowel found = a at index = 4 Vowel found = i at index = 6 Vowel found = o at index = 7
Check if a word contains at least one vowel with Regex in Java
// Check if a word contains at least one vowel with RegExp in Java
class Demo119 {
public static void main(String[] args) {
String word = "education";
if(word.matches(".*[aeiou].*")) {
System.out.println("Contains vowel");
} else {
System.out.println("no vowel found");
}
}
}
Output
Contains vowel
Find digits in a word with Regex in Java
// Find digits in a word with RegExp in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo120 {
public static void main(String[] args) {
String word = "Room123";
String regex = "\\d";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(word);
while (matcher.find()) {
System.out.println("Found digit = "+matcher.group()+" at index = "+matcher.start());
}
}
}
Output
Found digit = 1 at index = 4 Found digit = 2 at index = 5 Found digit = 3 at index = 6
Extract all numbers from a sentence with Regex in Java
// Extract all numbers from a sentence with RegExp in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo121 {
public static void main(String[] args) {
String text = "Order 3 cricket bats and 10 balls";
String regex ="\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println("Number = "+matcher.group());
}
}
}
Output
Number = 3 Number = 10
If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments