Regular Expressions in Java: Complete Guide with Code Examples
Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on patterns. In Java, working with regular expressions is implemented through two main classes: java.util.regex.Pattern (pattern compilation) and java.util.regex.Matcher (performing the search). In this article, we will break down the syntax, main methods, and look at practical examples that will help you confidently use regex in real projects.
1. Basics of Working with Regular Expressions in Java
Before moving on to examples, let's break down the key classes and their interaction.
Pattern Class
Pattern is a compiled representation of a regular expression. It is created using the static method Pattern.compile(). Without compilation, using regex is impossible.
Matcher Class
Matcher is the "engine" that performs a search based on a given pattern in a string. It is created using the method pattern.matcher(inputString).
Basic Metacharacter Syntax
.— any character (except newline)\\d— digit (0-9)\\w— letter, digit, or underscore\\s— whitespace character^— start of string$— end of string*— 0 or more repetitions+— 1 or more repetitions?— 0 or 1 repetition{n,m}— from n to m repetitions[]— character set (e.g.,[a-z]— any lowercase letter)()— capturing group
Example 1: Simple Phone Number Validation
import java.util.regex.*;
public class PhoneValidator { public static void main(String[] args) { String phone = "+7 (999) 123-45-67"; String regex = "^\\\\+7\\\\s\\\\(\\\\d{3}\\\\)\\\\s\\\\d{3}-\\\\d{2}-\\\\d{2}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(phone); if (matcher.matches()) { System.out.println("Phone number is valid"); } else { System.out.println("Phone number does not match the format"); } }}2. Matcher Methods: matches(), find() and Capturing Groups
Understanding the difference between matches() and find() is key to successfully working with regex in Java.
matches()— checks if the entire string matches the pattern (implicitly adds^and$).find()— searches for a substring matching the pattern anywhere in the string.group()— returns the found match or the value of a capturing group.
Example 2: Extracting Email Addresses from Text Using find() and Groups
import java.util.regex.*;
public class EmailExtractor { public static void main(String[] args) { String text = "Contacts: support@example.com, info@test.org and admin@site.net."; String regex = "([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\\\.([a-zA-Z]{2,})"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println("Full email: " + matcher.group()); System.out.println("Username: " + matcher.group(1)); System.out.println("Domain: " + matcher.group(2)); System.out.println("Zone: " + matcher.group(3)); System.out.println("---"); } }}Example 3: Password Validation Using matches()
Requirements: 8 to 20 characters, at least one uppercase letter, at