Java Regular Expressions (Regex)

Last Updated : 12 Jan 2026

The Java Regex or Regular Expression is an API used to define patterns for searching or manipulating strings.

It is widely used to define constraints on strings, such as password and email validation. After learning the Java Regex, you will be able to test your regular expressions using the Java Regex Tester tool.

The Java Regex API provides one interface and three classes in the java.util.regex package

java.util.regex package

The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package provides following classes and interfaces for regular expressions.

  1. MatchResult interface
  2. Matcher class
  3. Pattern class
  4. PatternSyntaxException class
Java Regex API

Matcher class

It implements the MatchResult interface. It is a regex engine which is used to perform match operations on a character sequence.

No.MethodDescription
1boolean matches()test whether the regular expression matches the pattern.
2boolean find()finds the next expression that matches the pattern.
3boolean find(int start)finds the next expression that matches the pattern from the given start number.
4String group()returns the matched subsequence.
5int start()returns the starting index of the matched subsequence.
6int end()returns the ending index of the matched subsequence.
7int groupCount()returns the total number of the matched subsequence.

Pattern class

It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.

No.MethodDescription
1static Pattern compile(String regex)compiles the given regex and returns the instance of the Pattern.
2Matcher matcher(CharSequence input)creates a matcher that matches the given input with the pattern.
3static boolean matches(String regex, CharSequence input)It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.
4String[] split(CharSequence input)splits the given input string around matches of given pattern.
5String pattern()returns the regex pattern.

Example of Java Regular Expressions

There are three ways to write the regex example in Java.

Example

Compile and Run

Output

true true true

Dot (.) Quantifier in Java Regex

In Java regular expressions, the dot (.) quantifier matches exactly one character, except a newline. It is commonly used when the exact character is not known but its position in the string matters.

Example

Consider the following example to understand the use of the dot (.) quantifier in Java regex.

Compile and Run

Java Regex Character Classes

Java Regex character classes are used to define a set or group of characters that can match a single character at a specific position in a string.

The following table shows different types of character classes in Java Regular Expressions and explains how each character class pattern is used to match specific sets or ranges of characters while performing pattern matching.

No.Character ClassDescription
1[abc]a, b, or c (simple class)
2[^abc]Any character except a, b, or c (negation)
3[a-zA-Z]a through z or A through Z, inclusive (range)
4[a-d[m-p]]a through d, or m through p: [a-dm-p] (union)
5[a-z&&[def]]d, e, or f (intersection)
6[a-z&&[^bc]]a through z, except for b and c: [ad-z] (subtraction)
7[a-z&&[^m-p]]a through z, and not m through p: [a-lq-z](subtraction)

Example

Consider the following example to understand the use of character classes in regular expressions:

Compile and Run

Java Regex Quantifiers

Java Regex Quantifiers define how many times a character, group, or character class can occur in a pattern. They are used to control the repetition of elements while matching strings.

The following table shows different types of quantifiers in Java Regular Expressions and explains how each quantifier controls the number of times a character or pattern can occur in a string.

RegexDescription
X?X occurs once or not at all
X+X occurs once or more times
X*X occurs zero or more times
X{n}X occurs n times only
X{n,}X occurs n or more times
X{y,z}X occurs at least y times but less than z times

Example

The following example demonstrates how different regex quantifiers (?, +, *) work with the character class [amn].

  • [amn]? (zero or one occurrence):
    The string can contain only one character from a, m, or n, or none at all. Any string with more than one character or repeated occurrences does not match.
  • [amn]+ (one or more occurrences):
    The string must contain at least one character from a, m, or n, and it can repeat multiple times. If any other character appears, the match fails.
  • [amn]* (zero or more occurrences):
    The string may contain any number of characters from a, m, or n, including zero occurrences. As long as no other characters are present, the match succeeds.
Compile and Run

Java Regex Metacharacters

Java Regex Metacharacters are special characters that have a predefined meaning in regular expressions and are used to define rules for pattern matching, such as position, repetition, or character types.

This table shows commonly used metacharacters in Java Regular Expressions along with their meanings, explaining how each metacharacter is used to match specific character types, positions, or boundaries in a string.

RegexDescription
.Any character (may or may not match terminator)
\dAny digits, short of [0-9]
\DAny non-digit, short for [^0-9]
\sAny whitespace character, short for [\t\n\x0B\f\r]
\SAny non-whitespace character, short for [^\s]
\wAny word character, short for [a-zA-Z_0-9]
\WAny non-word character, short for [^\w]
\bA word boundary
\BA non word boundary

Example

The following example demonstrates the use of regex metacharacters \d and \D:.

  • \d (digit):
    It matches exactly one digit from 0 to 9. If the input contains non-digit characters or more than one character, the match fails.
  • \D (non-digit):
    It matches exactly one non-digit character. If digits are present or the string has more than one character, the match does not succeed.
  • \D* (non-digit with quantifier):
    The * quantifier allows zero or more non-digit characters, so strings containing only non-digits of any length are matched successfully.

More Examples on Java Regex

Practice the following examples to strengthen your understanding of Java Regular Expressions. These examples cover pattern matching, validation, searching, replacing, and extracting information using regex.

Example 1: Alphanumeric String Validation (Fixed Length)

Example 2: Mobile Number Validation Using Regex

The following example demonstrates how to validate 10-digit numeric mobile numbers that must start with 7, 8, or 9, using character classes, quantifiers, and metacharacters.

Example 3: Java Regex Finder Tool

The following example demonstrates how to search and locate multiple occurrences of a regex pattern within a given text using the Pattern and Matcher classes.

Output:

Enter regex pattern: java
Enter text: this is java, do you know java
I found the text java starting at index 8 and ending at index 12
I found the text java starting at index 26 and ending at index 30

Example 4: Java Regex Features Demonstration

The following example demonstrates various regex operations such as:

  • Matching specific patterns
  • Finding words using boundaries
  • Replacing text
  • Splitting strings
  • Validating email addresses
  • Extracting domain names from URLs

Output:

Example 1: Matching a specific pattern
Does the text contain the word 'fox'? false

Example 2: Using Pattern and Matcher classes
3-letter words in the text:

Example 3: Replacing matched patterns
Original text: The cat sat on the mat
Replaced text: The dog sat on the mat

Example 4: Splitting text using regex
Fruits separated: apple banana orange grape

Example 5: Validating email addresses
Validating email addresses:
user@example.com: true
invalid.email.com: false
another.user@domain.co: true

Example 6: Extracting domain names from URLs
Domain extracted from URL: example.com

Example 5: Extracting Data Using Regex Patterns

The following example demonstrates how to extract:

  • Phone numbers
  • URLs
  • Email addresses
  • Dates

from a given text using regular expressions and the Matcher class.

Output:

Example 1: Extracting phone numbers from text
Phone numbers found in the text: 123-456-7890 987-654-3210 

Example 2: Extracting URLs from text
URLs found in the text: https://www.example.com http://another.example.org 

Example 3: Matching email addresses in text
Email addresses found in the text: email@example.com another.email@example.org 

Example 4: Finding dates in text
Dates found in the text: 2024-02-15 2024/02/20

Overall, regular expressions in Java provide a flexible and powerful way to work with strings, allowing you to perform complex matching and manipulation operations with relatively simple patterns.