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+");← Chapter 9 — Files & Regular Expressions
mixed
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.
matches checks whether all text fits a pattern.
Use escaped backslashes in Java strings for regex escapes.
boolean digits = "123".matches("\\d+");Pattern and Matcher can locate parts of text.
find searches within longer input.
java.util.regex.Pattern.compile("Java").matcher("Learn Java").find();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.
public class RegexDemo {
public static void main(String[] args) {
String rollNumber = "STU-104";
boolean valid = rollNumber.matches("STU-\\d{3}");
System.out.println(valid);
}
}