Master Java Regular Expression Examples With Code Snippets

Robert Jul 13, 2026

Mastering regular expressions (regex) can significantly enhance your Java coding experience. These powerful search patterns enable you to work with strings more effectively. If you're new to Java regex, here's a comprehensive guide with practical examples to help you grasp their application.

10 Java Regular Expression Examples You Should Know - Mkyong.com
10 Java Regular Expression Examples You Should Know - Mkyong.com

Regular expressions are a crucial aspect of many modern programming languages, and Java is no exception. They provide a concise and expressive way to match strings, which can be highly advantageous when working with text data. Let's dive into two fundamental topics: creating regex patterns and using them in Java.

10 Examples of Java Regular Expression Special or Meta Characters
10 Examples of Java Regular Expression Special or Meta Characters

Creating Regex Patterns

At the core of regex lies the concept of a pattern used to match strings. These patterns are composed of regular expressions, which are sequences of characters defining a search pattern. Java's regex engine uses backslashes (\) to introduce special sequences known as metacharacters.

10 Regular Expressions Every Java Programmer Should Learn
10 Regular Expressions Every Java Programmer Should Learn

Here are a few basic metacharacters and their uses:

  • . - Matches any character (except newline).
  • ^ - Matches the start of the line.
  • $ - Matches the end of the line.
  • * - Matches zero or more occurrences of the preceding character.
  • + - Matches one or more occurrences of the preceding character.
  • ? - Matches zero or one occurrence of the preceding character.
  • {} - Defines a specific quantity of the preceding character.
  • | - Acts as a logical OR between two patterns.
How to use Regular Expression in Java – Tutorial and Importance
How to use Regular Expression in Java – Tutorial and Importance

Character Classes

Character classes wrap a set of characters and match any character inside the class. You can define a character class using either [a-b] (which matches any character from 'a' to 'b') or \w (which matches any word character).

Here's an example that matches any word starting with a letter followed by exactly three digits:

Example of Java Regular Expressions
Example of Java Regular Expressions

\w[0-9]{3}

Boundaries

Boundaries are special positions within a string. The most important boundary is the word boundary \b, which matches the position where a word character is not followed or preceded by another word character.

Understand Java Regular Expression (Java Regex) with Examples
Understand Java Regular Expression (Java Regex) with Examples

For instance, the regex \b\w{3}\b matches exactly three-letter words, such as ' aplicaciΓ³n' in Spanish or 'cat' in English.

Using Regex in Java

Understanding Regular Expressions in JavaScript
Understanding Regular Expressions in JavaScript
Java Regular Expressions - Learn with its Classes and Interface
Java Regular Expressions - Learn with its Classes and Interface
a table with two different types of information
a table with two different types of information
a book cover with an image of a yellow and black background
a book cover with an image of a yellow and black background
How to Become a Hacker
How to Become a Hacker
Unlocking the Power of Regular Expressions with Examples
Unlocking the Power of Regular Expressions with Examples
Logical Operators in Java: Think Smarter, Code Better β˜•πŸš€
Logical Operators in Java: Think Smarter, Code Better β˜•πŸš€
an image of a computer screen with the words if else statement on it and two blocks of code
an image of a computer screen with the words if else statement on it and two blocks of code
Java if...else (With Examples)
Java if...else (With Examples)
β˜• Java Basics Cheat Sheet for Beginners | Learn Java in One Page πŸš€
β˜• Java Basics Cheat Sheet for Beginners | Learn Java in One Page πŸš€
30 Days of Java – Day 4 | Java If-Else Statement Explained for Beginners
30 Days of Java – Day 4 | Java If-Else Statement Explained for Beginners
JavaScript Regular Expressions (Regex) Cheat Sheet
JavaScript Regular Expressions (Regex) Cheat Sheet
Java Collection Framework: ArrayList Explained Visually
Java Collection Framework: ArrayList Explained Visually
How to use Switch Statement and Expression in Java? Tutorial with Examples
How to use Switch Statement and Expression in Java? Tutorial with Examples
β˜• Java Operators Cheat Sheet | Master Java Operators Easily πŸš€
β˜• Java Operators Cheat Sheet | Master Java Operators Easily πŸš€
πŸ”₯ JAVA LAMBDA EXPRESSIONS SIMPLIFIED! πŸš€
πŸ”₯ JAVA LAMBDA EXPRESSIONS SIMPLIFIED! πŸš€
a screen with the text 2 reverse an array description description description description description description description description description description description description description description description description description description description description description description description
a screen with the text 2 reverse an array description description description description description description description description description description description description description description description description description description description description description description description
Learn Java Collections Fast πŸš€ | ArrayList HashMap Set Queue Explained
Learn Java Collections Fast πŸš€ | ArrayList HashMap Set Queue Explained

Java provides a rich set of APIs to work with regex, particularly through the java.util.regex package. To use regex in Java, you'll commonly interact with the Pattern and Matcher classes.

The Pattern class represents a compiled regex pattern. To instantiate a Pattern object, you pass your regex pattern to the Pattern.compile() method:

Pattern pattern = Pattern.compile("\\d+"); // Matches one or more digits

Matching Input

After creating a Pattern object, you can use it to obtain a Matcher instance, which provides methods for checking and retrieving matches from a given input string:

String input = "Here are some numbers: 123 and some more: 456";
Matcher matcher = pattern.matcher(input);

boolean found = matcher.find(); // true if at least one match was found
int start = matcher.start(); // Start index of the first match
int end = matcher.end(); // End index of the first match
String matched = matcher.group(); // Text of the first match

You can also iterate through all matches using the while ( matcher.find() ) loop:

while (matcher.find()) {
    System.out.println("Found: " + matcher.group());
}

Replacing Text

Java regex also allows you to replace matched text with another string. You can achieve this using the Matcher.replaceAll() or String.replaceAll() methods:

  • Matcher.replaceAll(replacement) - Replaces all matches in the input sequence with the given replacement string.
  • String.replaceAll regex, replacement - Replaces all substrings of the given string that match the regex pattern with the given replacement.

Here's an example that replaces all matched numbers with the string "NUM:":

String output = matcher.replaceAll("NUM:");

Regular expressions are a powerful tool in Java, enabling you to work more efficiently with strings. With practice, you'll find regex to be an invaluable skill in your programming toolkit.

Now that you have a solid grasp of Java regular expressions, go ahead and explore more advanced topics, such as lookaheads, lookbehinds, and named groups. Happy coding!