Regular Expressions in Java: From Basics to Advanced Usage
Regular expressions (regex) are a powerful tool for working with text, allowing you to search, replace, and validate strings using complex patterns. In Java, support for regular expressions is implemented through the java.util.regex package, which provides two main classes: Pattern (compiles the pattern) and Matcher (performs search/replace operations).
In this article, we will explore how to effectively use regular expressions in Java, starting from basic syntax and ending with real-world examples from development practice.
1. Basics of Regular Expression Syntax in Java
Before moving on to Java code, it is important to master the basic metacharacters of regular expressions:
.— any single character (except newline)\\d— any digit (0-9)\\w— a letter, digit, or underscore\\s— a whitespace character (space, tab, newline)*— 0 or more repetitions of the preceding character+— 1 or more repetitions?— 0 or 1 repetition (makes the character optional)^— start of a line$— end of a line[...]— character class (e.g.,[a-z]— all lowercase letters)(...)— capturing group
Important: In Java, strings with regular expressions require double escaping. For example, to use \\d, you write "\\\\d" in code. This is because the backslash is first processed by the Java compiler and then passed to the regex engine.
2. Pattern and Matcher Classes — The Foundation of Working with regex in Java
The basic workflow for regular expressions in Java consists of three steps:
- Creating a
Patternobject by compiling the pattern string - Creating a
Matcherobject by calling thematcher()method on the string to be checked - Performing operations — searching, matching, replacing
Example 1: Checking if an entire string matches
import java.util.regex.Pattern;import java.util.regex.Matcher;
public class RegexExample { public static void main(String[] args) { // Check if the string is a valid email address String email = "user@example.com"; String emailPattern = "^[A-Za-z0-9+_.-]+@(.+)$"; Pattern pattern = Pattern.compile(emailPattern); Matcher matcher = pattern.matcher(email); if (matcher.matches()) { System.out.println("Email is valid"); } else { System.out.println("Email is invalid"); } }}The matches() method attempts to match the pattern against the entire string. If you need to check whether the string contains a match for the pattern (not necessarily the whole string), the find() method is used.
Example 2: Finding all occurrences of a pattern in a string
import java.util.regex.Pattern;import java.util.regex.Matcher;
public class FindExample { public static void main(String[] args) { String text = "Java 8, Java 11, Java 17 — these are versions of the Java language"; String regex = "Java\\\\s+\\\\d+"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println("Found: " + matcher.group() + " (position: " + matcher.start() + "-" + matcher.end() + ")"); } }}Execution result:
Found: Java 8 (position: 0-6)Found: Java 11 (position: 8-15)