Java RegEx


Regular Expressions, or RegEx for short, are patterns used to match and manipulate strings. They help you search, validate, or extract text based on specific patterns. For example, you can check if an email address is valid, find all numbers in a sentence, or replace certain words in a paragraph.

In Java, regular expressions are supported through the java.util.regex package, which provides two main classes:

  • Pattern – defines the pattern of the regular expression.

  • Matcher – performs operations like matching, finding, and replacing based on the defined pattern.

Let’s explore how these work in detail.

Basic RegEx Example

Here’s a simple example that checks if a string contains the word “Java”.

import java.util.regex.*;

public class RegExExample {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("Java");
        Matcher matcher = pattern.matcher("I love Java programming");
        boolean found = matcher.find();
        System.out.println("Match found: " + found);
    }
}

Output:

Match found: true

Here’s what happens:

  • Pattern.compile("Java") creates a pattern for the word “Java”.

  • matcher() applies that pattern to the input string.

  • find() checks if the word appears anywhere in the text.

Common RegEx Symbols

Here are some basic RegEx characters and their meanings:

Symbol Meaning Example Matches
. Any character (except newline) c.t cat, cut, cot
* 0 or more occurrences go*d gd, god, good
+ 1 or more occurrences go+d god, good
? 0 or 1 occurrence colou?r color, colour
\d Any digit (0–9) \d+ 123, 42
\D Non-digit \D+ abc, @#
\s Whitespace \s+ space, tab
\w Any letter, digit, or underscore \w+ Java123
^ Beginning of line ^Hello Hello world
$ End of line end$ This is the end

These symbols allow you to create flexible and complex search patterns.

Using Pattern and Matcher

You can use Pattern and Matcher to perform multiple types of operations. Let’s look at some common examples.

Example 1: Finding All Matches

import java.util.regex.*;

public class FindAll {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher("Order numbers: 25, 60, and 120");
        while (matcher.find()) {
            System.out.println("Found: " + matcher.group());
        }
    }
}

Output:

Found: 25
Found: 60
Found: 120

The find() method looks for the next match, and group() returns the actual text that matched.

Example 2: Validating an Email Address

import java.util.regex.*;

public class EmailValidator {
    public static void main(String[] args) {
        String email = "sneha123@gmail.com";
        String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";

        boolean isValid = Pattern.matches(regex, email);
        System.out.println("Valid email: " + isValid);
    }
}

Output:

Valid email: true

Here, the matches() method checks whether the entire string matches the given pattern.

Example 3: Replacing Text Using RegEx

You can replace parts of a string using the replaceAll() method.

import java.util.regex.*;

public class ReplaceExample {
    public static void main(String[] args) {
        String text = "Java is fun. Java is powerful.";
        String result = text.replaceAll("Java", "Python");
        System.out.println(result);
    }
}

Output:

Python is fun. Python is powerful.

This replaces all occurrences of “Java” with “Python”.

Pattern Flags in RegEx

You can use flags to modify how a pattern behaves. For example:

Flag Description
Pattern.CASE_INSENSITIVE Ignores case when matching
Pattern.MULTILINE Treats input as multiple lines
Pattern.DOTALL Allows . to match newline characters

Example:

Pattern pattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("I love JAVA and JavaScript");
while (matcher.find()) {
    System.out.println("Match: " + matcher.group());
}

Output:

Match: JAVA
Match: Java

Using Groups in RegEx

Groups are used to extract specific parts of a match. You define them using parentheses ().

import java.util.regex.*;

public class GroupExample {
    public static void main(String[] args) {
        String text = "Name: Priya, Age: 25";
        Pattern pattern = Pattern.compile("Name: (.*), Age: (\\d+)");
        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {
            System.out.println("Name: " + matcher.group(1));
            System.out.println("Age: " + matcher.group(2));
        }
    }
}

Output:

Name: Priya
Age: 25

Here, group(1) and group(2) correspond to the values captured inside parentheses.

Checking if a String Matches a Pattern

To check whether an entire string matches a given pattern, use matches() directly.

boolean result = Pattern.matches("[a-z]+", "hello");
System.out.println(result);

This will return true only if the entire string matches the pattern [a-z]+.

Escaping Special Characters

If you need to search for characters like . or ? literally, you must escape them with a double backslash \\.

Example:

String result = "1.5 version".replaceAll("\\.", ",");
System.out.println(result);

Output:

1,5 version

Summary of the Tutorial

Regular expressions in Java are a powerful tool for working with text. You can use them to find patterns, validate inputs, extract data, or modify strings. The key classes — Pattern and Matcher — provide flexibility to perform everything from basic matches to complex replacements.

Understanding common symbols like *, +, ?, \d, and \w helps you write cleaner and more effective RegEx patterns. Once you get comfortable with it, you’ll find that RegEx saves a lot of time in handling string-based tasks.


Practice Questions

  1. Write a Java program to check whether a given string contains the word “code” using RegEx.

  2. Create a program to find all numbers from a text like "There are 5 cats, 12 dogs, and 3 birds." and print them individually.

  3. Write a Java program to validate an email address using RegEx.

  4. Create a Java program to check whether a given string is a valid Indian mobile number (should start with 6–9 and have 10 digits).

  5. Write a Java program to replace all spaces in a string with underscores (_) using replaceAll() and RegEx.

  6. Create a Java program that validates if a string is a valid password. (Must contain at least one uppercase letter, one number, and be 8–15 characters long.)

  7. Write a Java program to check if a string starts with a capital letter using RegEx.

  8. Create a Java program that extracts the domain name from an email address using capturing groups. Example: from "priya123@gmail.com" extract "gmail".

  9. Write a Java program that replaces all digits in a string with the character *.

  10. Create a Java program that finds all words that start with a vowel (A, E, I, O, U) from a given sentence and prints them.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top