Login Register
×

Java Regular Expressions (RegEx)

In Java, Regular Expressions (RegEx) are a powerful tool to find and manage patterns in text. They help you search, check, or modify strings quickly and efficiently.

Java provides built-in support for Regular Expressions through the java.util.regex package.

What is a Regular Expression?

A Regular Expression (RegEx) is a sequence of characters that represents a search pattern. You can think of it like a “smart filter” that helps you find specific words, characters, or patterns inside a string.

For example, if you want to check whether a text contains a phone number, email address, or postal code, you can do it easily using a Regular Expression instead of writing long conditional statements.

Why Use Regular Expressions?

Regular Expressions are useful for many real-world tasks, such as:

  • Searching for specific patterns inside text (like finding all dates in a document).
  • Validating user inputs (like checking if an email or password format is correct).
  • Replacing or cleaning text (for example, removing unwanted characters).
  • Splitting text based on specific patterns (like separating words, numbers, or special symbols).

Java RegEx Framework

Java provides two main classes inside the java.util.regex package:

  1. Pattern: It is defines the pattern for the search.
  2. Matcher: Finds matches of that pattern inside a given string.

These two classes work together, first, you define a pattern using Pattern, and then use Matcher to check whether a specific string fits that pattern.

Syntax of Regular Expressions

1) . (Dot) → Matches any single character

The dot symbol (.) stands for any one character except a newline (\n).
It is helpful when you don’t care what the character is; you just want something to be there.

Example:

String pattern = "a.b";

Matches: acb, a1b, a_b
Does not match: ab (because there’s no character between a and b).

2) * (Asterisk) → Matches zero or more occurrences

The * symbol means the previous character or group can appear any number of times, including none.

Example:

String pattern = "go*d";

Matches: gd, god, good, goooood
Does not match: gdg

It means the letter o can appear zero or many times between g and d.

3) + (Plus) → Matches one or more occurrencess

The + symbol means the previous character or pattern should appear at least once.

Example:

String pattern = "ha+";

Matches: ha, haa, haaa
Does not match: h (because there’s no a)

It means, there must be one or more a characters after h.

4) ? (Question mark) → Matches zero or one occurrence

The ? symbol means the previous character or pattern can appear either once or not at all.

Example:

String pattern = "colou?r";

Matches: color, colour
Does not match: colouur

5) \d → Matches any digit (0–9)

The \d symbol represents any single digit from 0 to 9.

Example:

String pattern = "\\d\\d";

Matches: 12, 99
Does not match: ab

6) \w → Matches any word character

The \w symbol matches any letter (a–z, A–Z), digit (0–9), or underscore (_).

Example:

String pattern = "\\w\\w";

It matches: A1, ab, Z_
Does not match: @#

7) \s → Matches any whitespace

The \s symbol matches spaces, tabs, or newlines.

Example:

String pattern = "Java\\sCode";

Matches: Java Code
Does not match: JavaCode

8) ^ (Caret) → Matches the start of a line

The ^ symbol is used to check whether a string starts with a specific pattern.

Example:

String pattern = "^Hello";

Matches: Hello world
Does not match: Say Hello

9) $ (Dollar) → Matches the end of a line

The $ symbol checks if a string ends with a certain pattern.

Example:

String pattern = "end$";

Matches: This is the end
Does not match: end of story

How to Use RegEx in Java?

1. Matching a Pattern

When you want to check whether a string fits a certain pattern, you can use the Pattern and Matcher classes.

Example: Checking if a text contains both letters and numbers

import java.util.regex.*;

public class RegExMatchExample {
public static void main(String[] args) {
String text = "code123";
String pattern = "[a-zA-Z]+\\d+"; // Letters followed by digits

Pattern compiled = Pattern.compile(pattern);
Matcher match = compiled.matcher(text);

if (match.matches()) {
System.out.println("The text perfectly matches the pattern!");
} else {
System.out.println("The text does not match the pattern.");
}
}
}

Output:

The text perfectly matches the pattern!

2) Finding All Matches in a String

Sometimes you don’t want to check the whole string; you just want to find all parts that match a pattern. For this, we use the find() method inside a loop.

Example: Finding all 4-letter words

import java.util.regex.*;

public class FindAllWords {
public static void main(String[] args) {
String sentence = "Love code more each day";
String pattern = "\\b\\w{4}\\b"; // Words with exactly 4 characters

Pattern compiled = Pattern.compile(pattern);
Matcher match = compiled.matcher(sentence);

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

Output:

Found word: Love
Found word: code

3) Replacing Strings

The replaceAll() method helps you replace text that matches a pattern with something new. This is useful for formatting, cleaning, or transforming strings.

Example: Replace digits with stars

public class ReplaceWithRegex {
public static void main(String[] args) {
String text = "Order ID: 4587, Amount: 2999";
String result = text.replaceAll("\\d", "*");

System.out.println("Before: " + text);
System.out.println("After : " + result);
}
}

Output:

Before: Order ID: 4587, Amount: 2999
After : Order ID: ****, Amount: ****

4) Splitting Strings Using RegEx

You can use the split() method to divide a string into an array wherever a pattern is found. It’s often used for breaking sentences, CSV data, or logs.

Example: Splitting a sentence by spaces or commas

public class SplitUsingRegex {
public static void main(String[] args) {
String text = "apple, banana orange,grape";
String pattern = "[,\\s]+"; // Split by comma or space

String[] words = text.split(pattern);
for (String word : words) {
System.out.println(word);
}
}
}

Output:

apple
banana
orange
grape

Common Use Cases of RegEx in Java

1) Email Validation:

Email validation ensures that the entered email address follows a correct format or not. Like username@domain.com. For example

public class EmailValidation {
public static void main(String[] args) {
String email = "user.name2025@gmail.com";
String pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$";

if (email.matches(pattern)) {
System.out.println("Valid email address");
} else {
System.out.println("Invalid email address");
}
}
}

Output:

Valid email address

2) Password Validation:

Strong passwords are essential for application security. With RegEx, we can check that a password contains at least one uppercase letter, one digit, and a minimum of 8 characters.

For example:

    public class PasswordValidation {
    public static void main(String[] args) {
    String password = "JavaPro123";
    String pattern = "^(?=.*[A-Z])(?=.*\\d).{8,}$";

    if (password.matches(pattern)) {
    System.out.println("Strong password");
    } else {
    System.out.println("Weak password");
    }
    }
    }

    Output:

    Strong password

    3) Extracting Numbers from a Text

    Sometimes, you only need the numbers from a sentence, for example, extracting an order ID, price, or phone number from a message. For example:

      import java.util.regex.*;

      public class ExtractNumber {
      public static void main(String[] args) {
      String message = "Invoice No: 987654 generated successfully";
      String pattern = "\\d+";

      Pattern compiled = Pattern.compile(pattern);
      Matcher match = compiled.matcher(message);

      if (match.find()) {
      System.out.println("Extracted number: " + match.group());
      } else {
      System.out.println("No number found in text.");
      }
      }
      }

      Output:

      Extracted number: 987654

      Also Learn Important Topics of Java