codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

58 / 65 topics
56Java Wrapper Classes57Java Generics58Java RegEx59Java Threads60Java Lambda
Tutorials/Java Programming/Java RegEx
☕Java Programming

Java RegEx

Updated 2026-05-12
30 min read

Java RegEx

Regular expressions (RegEx) are a powerful tool for pattern matching and text manipulation in programming. In Java, the Pattern and Matcher classes provide comprehensive support for working with regular expressions. This tutorial will guide you through the basics of regex syntax, how to use the Pattern and Matcher classes, and advanced features like replaceAll.

Introduction

Regular expressions are sequences of characters that define a search pattern. They are widely used in text processing tasks such as searching, replacing, splitting, and validating strings. In Java, the java.util.regex package provides the necessary tools to work with regex.

Understanding regular expressions is crucial for developers who need to perform complex string manipulations or validations in their applications. Whether you're building a search engine, data validator, or text formatter, regex can simplify your code significantly.

Core Content

Pattern and Matcher Classes

The Pattern class represents a compiled regular expression, while the Matcher class is used to match this pattern against input strings. Here's how they work together:

  1. Compile the Regular Expression: Use the Pattern.compile() method to compile a regex string into a Pattern object.
  2. Create a Matcher: Use the pattern.matcher(input) method to create a Matcher object that will search the input string for matches of the pattern.

Example 1: Basic Pattern and Matcher Usage

BasicRegex.java
1import java.util.regex.*;
2
3public class BasicRegex {
4 public static void main(String[] args) {
5 String regex = "hello";
6 String input = "Hello, world!";
7
8 // Compile the regular expression
9 Pattern pattern = Pattern.compile(regex);
10
11 // Create a matcher for the input string
12 Matcher matcher = pattern.matcher(input);
13
14 // Check if the input contains the pattern
15 boolean found = matcher.find();
16 System.out.println("Found: " + found);
17 };
18}
Output
Found: false

In this example, the regex "hello" is case-sensitive. Since the input string "Hello, world!" starts with a capital 'H', the match fails.

Regular Expressions Syntax

Regular expressions in Java follow a syntax similar to other programming languages like Perl and JavaScript. Here are some common regex constructs:

ConstructDescription
.Matches any single character (except newline)
*Matches zero or more occurrences of the preceding element
+Matches one or more occurrences of the preceding element
?Matches zero or one occurrence of the preceding element
[]Character class; matches any single character inside the brackets
[^]Negated character class; matches any single character not inside the brackets
()Grouping; treats the enclosed elements as a single unit

Example 2: Advanced Regex Constructs

AdvancedRegex.java
1import java.util.regex.*;
2
3public class AdvancedRegex {
4 public static void main(String[] args) {
5 String regex = "h.*o";
6 String input = "Hello, world!";
7
8 // Compile the regular expression
9 Pattern pattern = Pattern.compile(regex);
10
11 // Create a matcher for the input string
12 Matcher matcher = pattern.matcher(input);
13
14 // Check if the input contains the pattern
15 boolean found = matcher.find();
16 System.out.println("Found: " + found);
17 }
18}
Output
Found: true

In this example, the regex "h.*o" matches any string that starts with 'h', followed by zero or more characters, and ends with 'o'. The input string "Hello, world!" satisfies this pattern.

replaceAll Method

The Matcher class provides various methods for manipulating strings based on the matched patterns. One of the most useful methods is replaceAll(), which replaces all occurrences of the pattern in the input string with a specified replacement string.

Example 3: Using replaceAll

ReplaceAllExample.java
1import java.util.regex.*;
2
3public class ReplaceAllExample {
4 public static void main(String[] args) {
5 String regex = "world";
6 String input = "Hello, world!";
7 String replacement = "Java";
8
9 // Compile the regular expression
10 Pattern pattern = Pattern.compile(regex);
11
12 // Create a matcher for the input string
13 Matcher matcher = pattern.matcher(input);
14
15 // Replace all occurrences of the pattern
16 String result = matcher.replaceAll(replacement);
17 System.out.println("Result: " + result);
18 }
19}
Output
Result: Hello, Java!

In this example, the regex "world" matches the word "world" in the input string. The replaceAll() method replaces it with "Java", resulting in the output "Hello, Java!".

Practical Example

Let's create a practical example that demonstrates how to use regular expressions to validate email addresses and replace them if necessary.

Example 4: Email Validation and Replacement

EmailValidator.java
1import java.util.regex.*;
2
3public class EmailValidator {
4 public static void main(String[] args) {
5 String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6}";
6 String input = "Contact us at info@example.com or support@sample.org";
7 String replacement = "contact@codingstuff.io";
8
9 // Compile the regular expression
10 Pattern pattern = Pattern.compile(regex);
11
12 // Create a matcher for the input string
13 Matcher matcher = pattern.matcher(input);
14
15 // Check if the input contains valid emails
16 while (matcher.find()) {
17 System.out.println("Found email: " + matcher.group());
18 }
19
20 // Replace all occurrences of the pattern
21 String result = matcher.replaceAll(replacement);
22 System.out.println("Result: " + result);
23 }
24}
Output
Found email: info@example.com
Found email: support@sample.org
Result: Contact us at contact@codingstuff.io or contact@codingstuff.io

In this example, the regex "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}" matches valid email addresses. The program first prints all found emails and then replaces them with "contact@codingstuff.io".

Summary

Key ConceptDescription
PatternRepresents a compiled regular expression
MatcherUsed to match the pattern against input strings
replaceAllReplaces all occurrences of the pattern in the input string
  • Regular expressions are powerful for pattern matching and text manipulation.
  • The Pattern and Matcher classes provide the necessary tools to work with regex in Java.
  • Advanced regex constructs like character classes, quantifiers, and groups allow for complex pattern definitions.
  • The replaceAll() method is useful for replacing matched patterns in strings.

What's Next?

Now that you have a solid understanding of regular expressions in Java, it's time to explore concurrency and multithreading. In the next tutorial, we'll dive into how to create and manage threads in Java, enabling your applications to perform multiple tasks simultaneously. Stay tuned!


PreviousJava GenericsNext Java Threads

Recommended Gear

Java GenericsJava Threads