Regex Example in java

Java Regex Examples: 6 Practical Programs with Source Code (2026) | D.Tech Academic

Java Regex Examples: 6 Practical Programs with Source Code (2026)

Last Updated: | Author: Deep Singh

Regular expressions are one of those Java features that feel confusing at first but become incredibly powerful once you understand them. Whether you're validating user input, extracting specific words from text, or parsing data, regex saves you from writing dozens of lines of manual string manipulation.

In this tutorial, you'll find six practical Java regex examples. Each one solves a real problem you'll run into: finding uppercase words, detecting numbers, extracting special characters, splitting on whitespace, pulling vowels out of a string, and validating common input formats like email, mobile numbers, and passwords.

1. Find Words That Contain Uppercase Letters

This program splits a sentence into words and prints any word that contains at least one uppercase letter. The regex (.*)([A-Z]+)(.*) matches any string with an uppercase letter somewhere in it.

public class Example1 {
    public static void main(String[] args) {
        String msg = "hello frIends how1 r U ?";
        String[] t = msg.split(" ");

        for (int i = 0; i < t.length; i++) {
            if (t[i].matches("(.*)([A-Z]+)(.*)")) {
                System.out.println(t[i]);
            }
        }
    }
}

Output:

frIends
U

How it works: (.*) matches any characters, ([A-Z]+) matches one or more uppercase letters, and (.*) matches the rest. Since matches() requires the whole string to match, this pattern succeeds only when an uppercase letter appears somewhere.

2. Find Words That Contain Numbers

Same pattern as above, but this time we look for digits using [0-9].

public class Example2 {
    public static void main(String[] args) {
        String msg = "1hello fr1ends how1 r ?";
        String[] t = msg.split(" ");

        for (int i = 0; i < t.length; i++) {
            if (t[i].matches("(.*)([0-9]+)(.*)")) {
                System.out.println(t[i]);
            }
        }
    }
}

Output:

1hello
fr1ends
how1

How it works: The pattern requires at least one digit [0-9]+ to appear anywhere in the word. Words without any digits are skipped.

3. Find Words That Contain Special Characters

Use a character class listing the special characters you care about. Inside square brackets, most special characters lose their special meaning, so you can list them directly.

public class Example3 {
    public static void main(String[] args) {
        String msg = "1hello fr1e%ds how1 r ?";
        String[] t = msg.split(" ");

        for (int i = 0; i < t.length; i++) {
            if (t[i].matches("(.*)([!@#$%^&*]+)(.*)")) {
                System.out.println(t[i]);
            }
        }
    }
}

Output:

fr1e%ds
?

Note: The ? was matched because ? appears in our pattern inside the character class. If you don't want that, remove it from the list. The pattern in this example intentionally excludes ? from being treated as a regex quantifier by placing it inside a character class.

4. Split a String on Multiple Whitespaces

When you have words separated by more than one space, a plain split(" ") leaves empty strings in the result. Use \\s+ to treat any run of whitespace as a single separator.

public class Example4 {
    public static void main(String[] args) {
        String msg = "hello   friends    how    r   u ?";
        String[] t = msg.split("\\s+");

        for (int i = 0; i < t.length; i++) {
            System.out.println(t[i]);
        }
    }
}

Output:

hello
friends
how
r
u
?

Why \\s+ instead of ? \s matches any whitespace character (space, tab, newline) and + means "one or more". So any run of whitespace is treated as one separator. In Java strings, you write "\\s+" because the backslash itself needs escaping.

5. Extract Vowels from a String

There are two ways to pull vowels out of a sentence. The example below shows both — the first keeps only vowels, the second removes them.

public class Example5 {
    public static void main(String[] args) {
        String msg = "hello friends how r u ?";

        // Approach 1: Remove all consonants to leave vowels
        String onlyVowels = msg.replaceAll(
            "[BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz]", "");
        System.out.println("Vowels only: " + onlyVowels);

        // Approach 2: Remove all vowels to leave consonants
        String onlyConsonants = msg.replaceAll(
            "[AEIOUaeiou]", "");
        System.out.println("Consonants only: " + onlyConsonants);
    }
}

Output:

Vowels only: eo ie o u
Consonants only: hll frnds hw r  ?

How it works: replaceAll() replaces every match of the regex with the given replacement. Passing "" removes all matches. Both approaches work — pick whichever is easier to read.

6. Validation Patterns (Email, Mobile, Password, Name)

This is where regex earns its keep. Instead of writing five different validation methods from scratch, you define one pattern per rule and let Java do the matching. Here's a complete utility class covering the most common validation cases.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {

    // Email: username@domain.tld
    private static final String EMAIL_PATTERN =
        "^[a-zA-Z0-9]{1,20}@[a-zA-Z]{1,20}\\.[a-zA-Z]{2,3}$";

    // Mobile: exactly 10 digits
    private static final String MOBILE_PATTERN = "\\d{10}";

    // Full name: letters and spaces only
    private static final String FULL_NAME_PATTERN = "^[a-zA-Z\\s]+$";

    // Password: at least one digit, lowercase, uppercase, and special char
    // between 6 and 15 characters total
    private static final String PASSWORD_PATTERN =
        "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!?&()@$%#]).{6,15})";

    // Digit-with-letter: contains at least one digit somewhere
    private static final String DIGIT_WITH_LETTER = "(.*)(\\d+)(.*)";

    public boolean digitWithLetter(String data) {
        return Pattern.compile(DIGIT_WITH_LETTER)
                .matcher(data)
                .find();
    }

    public boolean emailValidation(String email) {
        return Pattern.compile(EMAIL_PATTERN)
                .matcher(email)
                .matches();
    }

    public boolean mobileNumber(String mobile) {
        return Pattern.compile(MOBILE_PATTERN)
                .matcher(mobile)
                .matches();
    }

    public boolean fullName(String name) {
        return Pattern.compile(FULL_NAME_PATTERN)
                .matcher(name)
                .matches();
    }

    public boolean passwordValidation(String password) {
        return Pattern.compile(PASSWORD_PATTERN)
                .matcher(password)
                .matches();
    }

    public void printNamesWithoutSpaces(String names) {
        String[] data = names.split("\\s+");
        for (String n : data) {
            System.out.println(n);
        }
    }

    public static void main(String[] args) {
        Regex r = new Regex();

        System.out.println("Email valid: " + r.emailValidation("deep44@gmail.com"));
        System.out.println("Mobile valid: " + r.mobileNumber("8224898008"));
        System.out.println("Full name valid: " + r.fullName("Deep Singh"));
        System.out.println("Password valid: " + r.passwordValidation("eWp$d1h"));
        System.out.println("Has digit: " + r.digitWithLetter("deep1"));
    }
}

Output:

Email valid: true
Mobile valid: true
Full name valid: true
Password valid: true
Has digit: true

Breaking Down the Patterns

  • Email: ^[a-zA-Z0-9]{1,20}@[a-zA-Z]{1,20}\.[a-zA-Z]{2,3}$ — username, then @, then domain, then a dot, then a 2–3 letter TLD. The ^ and $ anchors force the entire string to match.
  • Mobile: \\d{10} — exactly ten digits, no more, no less.
  • Full name: ^[a-zA-Z\\s]+$ — letters and spaces only.
  • Password: (?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!?&()@$%#]).{6,15} — a series of lookaheads, each checking that the password contains at least one of the required character types, then .{6,15} ensures the length is between 6 and 15.

Understanding Lookaheads

The password pattern uses positive lookaheads: (?=...). A lookahead checks whether the pattern inside it matches ahead of the current position, but doesn't consume any characters. Chaining several lookaheads together lets you enforce multiple rules simultaneously without writing a long alternation.

For example, (?=.*\\d) means "somewhere later in the string, there must be a digit". The .* is important — it lets the lookahead scan the entire remaining string rather than just the next character.

Wrapping Up

You now have six practical Java regex examples covering text detection, splitting, extraction, and validation. These are the patterns you'll reach for most often in real projects — form validation, log parsing, text processing, and data cleanup.

A few tips as you build on this:

  • Escape backslashes in Java strings. Regex \d becomes "\\d" in Java. This trips up almost everyone the first time.
  • Use matches() for whole-string validation, find() for searching within text. They serve different purposes, and mixing them up is a common source of bugs.
  • Anchor your validation patterns. Always use ^ and $ when the entire string must match, or you'll get false positives on partial input.
  • Test your regex. Use a tool like regex101.com to experiment quickly before committing to code. It shows you exactly what each part of your pattern matches.
  • Precompile patterns that run in loops. Pattern.compile() is expensive. If you're matching inside a loop, compile once and reuse the Pattern instance.
  • Keep validation simple. Regex is great for format checks, but complex business rules (password hashing, rate limiting, duplicate checks) belong in code, not in a regex.

You might also find these helpful:

No comments: