← Back to Core Java Course | Chapter 6: Strings | Lesson 5 of 5

Java Regular Expressions

A regular expression is a pattern for finding text, like a stencil that fits only certain shapes. Java uses Pattern and Matcher to search, replace and split with it.
Syntax
java
import java.util.regex.*;

Pattern pattern = Pattern.compile("regex");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    matcher.group();
}

Pattern and Matcher Classes

Java's regex support lives in java.util.regex, centered on two classes: Pattern compiles a regular expression once for reuse, and Matcher applies that compiled pattern against a specific input string to search, find, or check for matches.

Example: Pattern and Matcher Classes

java
// Import java.util.regex.Pattern so it can be used by its short name
import java.util.regex.Pattern;
// Import java.util.regex.Matcher so it can be used by its short name
import java.util.regex.Matcher;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		Pattern pattern = Pattern.compile("cat");
		Matcher matcher = pattern.matcher("The cat sat");
		// Print a line to the console
		System.out.println(matcher.find());
	}
}

Character Classes

Character classes, written in square brackets like [aeiou] or [0-9], match any single character from the set you list — they're the building block for matching things like vowels, digit ranges, or a specific list of allowed symbols without writing out every alternative explicitly.

Example: Character Classes

java
public class Main {
	public static void main(String[] args) {
		System.out.println("hello".matches("[aeiou]+")); // false: not all vowels
		System.out.println("a1".matches("[0-9]")); // false
		System.out.println("5".matches("[0-9]"));
	}
}

Using Quantifiers

Quantifiers control repetition: * means zero or more, + means one or more, ? means optional (zero or one), and {n,m} lets you specify an exact or bounded repeat count, like \d{3} for exactly three digits.

Example: Using Quantifiers

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println("123".matches("\\d{3}"));
		// Print a line to the console
		System.out.println("color".matches("colou?r"));
		System.out.println("aaa".matches("a+"));
	}
}

Replacing with Regex

replaceAll() swaps every substring matching a regex pattern with a replacement string in one call, while replaceFirst() stops after the first match — both are convenient for cleanup tasks like stripping punctuation or normalizing whitespace.

Example: Replacing with Regex

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare text and set it to "cat bat rat"
		String text = "cat bat rat";
		// Print a line to the console
		System.out.println(text.replaceAll("at", "og"));
		// Print a line to the console
		System.out.println(text.replaceFirst("at", "og"));
	}
}

Splitting Strings with Regex

split() uses a regex as the delimiter to break a String into an array of pieces, which is more flexible than splitting on a single fixed character — for example, \s+ splits on any run of one or more whitespace characters, collapsing multiple spaces into a single split point.

Example: Splitting Strings with Regex

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare text and set it to "one   two  three"
		String text = "one   two  three";
		// Declare parts and set it to text.split("//s+")
		String[] parts = text.split("\\s+");
		for (String p : parts) {
			// Print a line to the console
			System.out.println(p);
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to escape backslashes in Java strings, so \d must be written "\\d".
  2. Calling matcher.group() without a successful find() or matches(), which throws IllegalStateException.
  3. Using matches() when partial matches are needed, since it must match the whole string.
Chapter Summary
  • Strings are objects with many built-in methods, and StringBuilder and StringBuffer allow efficient modification.
  • String formatting shapes text output.
  • Regular expressions match and process text patterns.
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.