Regular Expressions in Java with Examples
Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on a pattern. In Java, working with regular expressions is implemented through the java.util.regex package, which includes two main classes: Pattern and Matcher. In this article, we will cover the syntax of regular expressions, methods for working with them, and provide practical examples in Java.
1. Basics of Regular Expression Syntax
A regular expression defines a pattern for searching strings. Here are the basic constructs:
.— any character (except newline).\\d— a digit (0-9).\\w— a letter, digit, or underscore (Latin).\\s— a whitespace character (space, tab, newline).[abc]— one of the characters a, b, or c.[^abc]— any character except a, b, c.*— zero or more repetitions.+— one or more repetitions.?— zero or one repetition.{n,m}— from n to m repetitions.^— start of the string.$— end of the string.|— logical OR.()— capturing group.
Escaping in Java: in Java string literals, the backslash \\ is an escape character. To pass, for example, \\d in regex, you need to write "\\\\d". For a dot — "\\\\.".
2. Pattern and Matcher Classes
Working with regular expressions in Java starts with compiling the pattern:
import java.util.regex.Pattern;import java.util.regex.Matcher;
public class RegexExample { public static void main(String[] args) { // Compile the pattern Pattern pattern = Pattern.compile("\\\\d+"); // Create a Matcher for the string Matcher matcher = pattern.matcher("Price: 150 rubles, discount 20%"); // Find all matches while (matcher.find()) { System.out.println("Found: " + matcher.group()); } }}Output:
Found: 150Found: 20Main methods of Matcher:
find()— searches for the next match (can be called multiple times).matches()— checks if the entire string matches the pattern (requires a full match).lookingAt()— checks if the string starts with the pattern.group()— returns the found substring (or a specific group).groupCount()— the number of capturing groups.
3. Practical Examples
3.1. Email Address Validation
Let's check if a string is a valid email (simplified version):
public class EmailValidator { public static boolean isValidEmail(String email) { String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(email); return matcher.matches(); }
public static void main(String[] args) { System.out.println(isValidEmail("test@example.com")); // true System.out.println(isValidEmail("invalid-email")); // false }}Pattern explanation:
^[a-zA-Z0-9._%+-]+— local part (letters, digits, dots, underscores, etc.).@— the @ symbol.[a-zA-Z0-9.-]+— domain (letters, digits, dots, hyphens).\\\\.[a-zA-Z]{2,}$— dot and top-level domain (at least 2 characters).