← Chapter 9 — Files & Regular Expressions

33. Regular Expressions

mixed

Description

Regular expressions describe patterns in text. In Java, String methods and the Pattern API can use them to search, split, replace, or validate input.

Start with small patterns and test them with realistic examples. A regex that is clever but unreadable is difficult to maintain.

Subtopics

Matching

Description

matches checks whether all text fits a pattern.

Explanation

Use escaped backslashes in Java strings for regex escapes.

Example

boolean digits = "123".matches("\\d+");

Finding patterns

Description

Pattern and Matcher can locate parts of text.

Explanation

find searches within longer input.

Example

java.util.regex.Pattern.compile("Java").matcher("Learn Java").find();

Explanation

A Java string literal adds its own escaping layer. The regex \d is written as "\\d" in Java source because the first backslash escapes the second for the String.

Example

public class RegexDemo {
    public static void main(String[] args) {
        String rollNumber = "STU-104";
        boolean valid = rollNumber.matches("STU-\\d{3}");
        System.out.println(valid);
    }
}

Key points

  • Regexes describe text patterns.
  • matches checks the entire string.
  • Backslashes are escaped in Java strings.

Open reference