Regular Expressions in Java: From Theory to Practice
\nRegular expressions (regex) are a powerful tool for searching, replacing, and validating text. In Java, working with them is implemented through the java.util.regex package, which includes two main classes: Pattern and Matcher. In this article, we will break down the syntax, key methods, and solidify our knowledge with real code examples.
The material will be useful both for beginners just getting acquainted with Java and for experienced developers looking to refresh their knowledge. All examples can be run immediately in your IDE.
\n\n1. Basics of Working with Pattern and Matcher
\nAny work with regex in Java begins with compiling a pattern via Pattern.compile(). After that, a Matcher object is created, which applies the pattern to the string.
Let's look at a simple example: finding all digits in a text.
\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegexDemo {\n public static void main(String[] args) {\n String text = "Java version 21 was released in 2023";\n String regex = "\\\\d+"; // one or more digits\n\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n\n while (matcher.find()) {\n System.out.println("Found: " + matcher.group());\n }\n }\n}\nProgram output:
\nFound: 21\nFound: 2023\nNote the double backslash \\\\d — in Java, a string literal requires escaping the backslash. If you need to specify \\d in regex, you write \\\\d in code.
2. Regular Expression Syntax: Metacharacters and Quantifiers
\nTo use regex effectively, it's important to remember the basic metacharacters:
\n- \n
.— any character (except line break); \n \\\\d— a digit (equivalent to[0-9]); \n \\\\w— a letter, digit, or underscore ([a-zA-Z0-9_]); \n \\\\s— a whitespace character; \n ^— start of a line; \n $— end of a line. \n
Quantifiers control the number of repetitions:
\n- \n
+— one or more times; \n *— zero or more times; \n ?— zero or one time; \n {n}— exactly n times; \n {n,m}— from n to m times. \n
Example: let's find all words consisting only of Latin letters, with a length of 3 to 5 characters.
\nString text = "Java regex example for beginners";\nString regex = "\\\\b[a-zA-Z]{3,5}\\\\b";\n\nPattern pattern = Pattern.compile(regex);\nMatcher matcher = pattern.matcher(text);\n\nwhile (matcher.find()) {\n System.out.println(matcher.group());\n}\n// Output: Java, regex, for\nThe word boundary \\\\b prevents partial matches (for example, "Java" will not be part of "JavaScript").
3. Practical Examples: Validation and Data Extraction
\nLet's move on to tasks that are often encountered in real development.
\n\n3.1. Email Address Validation
\nA simple check: presence of the "@" symbol and a domain.
\npublic static boolean isValidEmail(String email) {\n String regex = "^[\\\\w.-]+@[\\\\w.-]+\\\\.\\\\w{2,}$";\n return Pattern.matches(regex, email);\n}\n\npublic static void main(String[] args) {\n System.out.println(isValidEmail("user@example.com")); // true\n System.out.println(isValidEmail("invalid-email")); // false\n}\nThe Pattern.matches() method automatically checks the entire string (equivalent to matcher.matches()).
3.2. Extracting Phone Numbers
\nSuppose the text contains numbers in the format "+7 (999) 123-45-67".
\nString text = "Contact: +