Java Regular Expressions (Regex)
100%

Java Regular Expressions (Regex)

A Regular Expression (Regex) is a pattern used to search, match, and validate text. In Java, regular expressions are commonly used for checking email formats, finding numbers, replacing text, and validating user input.

1. Introduction to Regex

Java provides the java.util.regex package for working with regular expressions.

Two important classes are:

  • Pattern — represents a regular expression pattern.
  • Matcher — performs matching operations on text.

Example: the pattern "cat" matches the word "cat".

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        System.out.println(
            Pattern.matches("cat", "cat")
        );

        System.out.println(
            Pattern.matches("cat", "dog")
        );
    }
}
Output:
true
false
Pattern.matches() checks whether the entire input matches the pattern, not just a part of the input.
2. Using the Pattern and Matcher Classes

Use Pattern.compile() to create a pattern and matcher() to check text against it.

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

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("Java");

        Matcher matcher = pattern.matcher("I am learning Java");

        System.out.println(matcher.find());
    }
}
Output:
true

The find() method returns true when it finds a matching part of the text.

3. Important Regex Characters
Pattern Meaning Example Match
. Matches one character except line terminators by default. c.t matches cat
^ Beginning of input or line, depending on mode. ^Java
$ End of input or line, depending on mode. Java$
* Zero or more repetitions. ab* matches a, ab, abb
+ One or more repetitions. ab+ matches ab, abb
? Zero or one repetition. colou?r
[abc] Matches one listed character. a, b, or c
[0-9] Matches one digit. 5
{2} Exactly two repetitions of the preceding item. [0-9]{2}
4. Matching Digits

Use \\d in a Java string to represent the regex digit pattern \d.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        System.out.println(
            Pattern.matches("\\d+", "12345")
        );

        System.out.println(
            Pattern.matches("\\d+", "12abc")
        );
    }
}
Output:
true
false

Here, \\d+ means one or more digits. The entire input must contain only digits for Pattern.matches() to return true.

5. Matching Letters

The pattern [a-zA-Z]+ matches one or more English letters, including uppercase and lowercase letters.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        System.out.println(
            Pattern.matches("[a-zA-Z]+", "Java")
        );

        System.out.println(
            Pattern.matches("[a-zA-Z]+", "Java123")
        );
    }
}
Output:
true
false

The second input contains digits, so it does not match the letters-only pattern.

6. Finding Numbers in Text

Use Matcher.find() to locate numbers inside a larger string.

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

public class Main {
    public static void main(String[] args) {
        String text = "I have 25 books and 10 pens.";

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}
Output:
25
10

The group() method returns the text matched by the most recent successful match.

7. Replacing Text with Regex

The replaceAll() method replaces every part of a string that matches a regular expression.

public class Main {
    public static void main(String[] args) {
        String text = "Java123 is easy456";

        String result = text.replaceAll("\\d+", "");

        System.out.println(result);
    }
}
Output:
Java is easy

The pattern \\d+ matches one or more digits, which are removed in this example.

8. Splitting a String with Regex

The split() method can divide a string using a regular expression as the separator.

public class Main {
    public static void main(String[] args) {
        String text = "Apple,Banana,Orange";

        String[] fruits = text.split(",");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
Output:
Apple
Banana
Orange

You can also split on one or more spaces using "\\s+".

9. Validating a Mobile Number

For a simple example, the following pattern checks whether a string contains exactly 10 digits.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String mobile = "9876543210";

        boolean valid = Pattern.matches(
            "[0-9]{10}",
            mobile
        );

        System.out.println("Valid: " + valid);
    }
}
Output:
Valid: true
This checks only the format of 10 digits. It does not verify whether the number is assigned, active, or valid under a country's complete numbering rules.
10. Validating an Email Format

A simple regular expression can check the basic shape of an email address.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String email = "student@example.com";

        String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";

        boolean valid = Pattern.matches(regex, email);

        System.out.println("Valid format: " + valid);
    }
}
Output:
Valid format: true
This is a basic format check, not complete email validation. It does not confirm that the email address exists or can receive messages.
11. Case-Insensitive Matching

Use Pattern.CASE_INSENSITIVE when uppercase and lowercase differences should be ignored.

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

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile(
            "java",
            Pattern.CASE_INSENSITIVE
        );

        Matcher matcher = pattern.matcher("I LIKE JAVA");

        System.out.println(matcher.find());
    }
}
Output:
true
12. Common Regex Patterns
Regex Meaning
\\d A digit.
\\D A non-digit.
\\s A whitespace character.
\\S A non-whitespace character.
\\w A word character, typically a letter, digit, or underscore in default mode.
\\W A character that is not a word character.
[A-Z] An uppercase English letter.
[a-z] A lowercase English letter.
[0-9]{4} Exactly four digits.
^Hello Text beginning with Hello.
In Java string literals, regex backslashes usually need to be doubled. For example, write "\\d+" in Java code to pass \d+ to the regex engine.
13. Java Regex Assignments
  1. Check whether the string "12345" contains only digits.
  2. Check whether the string "Hello" contains only English letters.
  3. Find all numbers in "I am 20 years old and have 5 books.".
  4. Remove all digits from "Java123Programming456".
  5. Split "Red,Green,Blue" into separate words.
  6. Check whether a string contains exactly 10 digits.
  7. Check the basic format of an email address using regex.
  8. Find every occurrence of the word "Java" in a sentence.
  9. Replace multiple spaces with a single space.
  10. Perform a case-insensitive search for "python" in a sentence.

Quick Quiz: Java Regex

Select the correct answer for each question.

1. Which Java class represents a regex pattern?



2. What does the regex pattern \\d+ match?



3. Which Matcher method searches for a matching part of the text?