Regular Expressions in Java with Examples: In Practice

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in Java: From Theory to Practice

\n

Regular 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.

\n

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\n

1. Basics of Working with Pattern and Matcher

\n

Any 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.

\n

Let's look at a simple example: finding all digits in a text.

\n
import 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}
\n

Program output:

\n
Found: 21\nFound: 2023
\n

Note 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.

\n\n

2. Regular Expression Syntax: Metacharacters and Quantifiers

\n

To 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
\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
\n

Example: let's find all words consisting only of Latin letters, with a length of 3 to 5 characters.

\n
String 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
\n

The word boundary \\\\b prevents partial matches (for example, "Java" will not be part of "JavaScript").

\n\n

3. Practical Examples: Validation and Data Extraction

\n

Let's move on to tasks that are often encountered in real development.

\n\n

3.1. Email Address Validation

\n

A simple check: presence of the "@" symbol and a domain.

\n
public 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}
\n

The Pattern.matches() method automatically checks the entire string (equivalent to matcher.matches()).

\n\n

3.2. Extracting Phone Numbers

\n

Suppose the text contains numbers in the format "+7 (999) 123-45-67".

\n
String text = "Contact: +                

Blogs

Book Recommendations