← Back to Chapters

Regular Expressions

? Regular Expressions

? Quick Overview

Regular Expressions (Regex) in Java provide a powerful way to search, match, validate, and manipulate text using patterns. In Advanced Java, regex is heavily used for validation, parsing logs, processing user input, and backend text handling.

? Key Concepts

  • Pattern Compiled representation of a regex
  • Matcher Engine that matches patterns against text
  • Metacharacters Special symbols like ., *, +
  • Quantifiers Control repetition
  • Character Classes Sets like [a-z]

? Live Regex Playground

Type a pattern and text below to see the Java Matcher engine concept in action.

 
Order ID: 99281, Qty: 5

? Syntax & Theory

Java regex is provided by the java.util.regex package. The two core classes are:

  • Pattern — defines the regex
  • Matcher — applies the pattern to text
? View Code Example
// Import regex classes
import java.util.regex.Pattern;
import java.util.regex.Matcher;

? Code Example — Basic Matching

? View Code Example
// Check if a string contains only digits
String input = "12345";
String regex = "\\d+";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

if (matcher.matches()) {
System.out.println("Valid number");
} else {
System.out.println("Invalid number");
}

? Live Output / Explanation

The regex \d+ matches one or more digits. Since the input contains only digits, the matcher returns true.

? Code Example — Email Validation

? View Code Example
// Validate an email address using regex
String email = "user@example.com";
String regex = "^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);

System.out.println(matcher.matches());

? Live Output / Explanation

This pattern checks username, domain, and extension format. The output will be true for a valid email structure.

? Tips & Best Practices

  • Always escape backslashes properly in Java strings
  • Use matches() for full string match
  • Use find() for partial matches
  • Precompile patterns for performance

? Try It Yourself

  • Write a regex to validate a mobile number
  • Extract all numbers from a sentence
  • Check password strength using regex
  • Split a CSV string using regex