Java matches Method Guide

The matches function in Java is used to determine if a string matches a specified regular expression.

The functionality of the matches function includes:

  1. Check if a string completely matches a regular expression: return true if the string matches the regular expression exactly, otherwise return false.
  2. Check if a string contains a substring that matches a regular expression: return true if there is a matching substring, otherwise return false.
  3. Determine if a string follows a specified format by using regular expressions to define the format and the matches function to verify compliance.
  4. Validate the input’s legitimacy: Regular expressions can be defined as rules used to verify the legality of user input, and the matches function can determine if the user input adheres to those rules.

It is important to note that the matches function can only determine if the entire string matches the regular expression. If there is a substring within the string that matches the regular expression but the entire string does not, the matches function will still return false.

For example, the following code uses the matches function to determine if a string is a valid phone number:

String phoneNumber = "13812345678";
if (phoneNumber.matches("1[3456789]\\d{9}")) {
    System.out.println("合法的手机号码");
} else {
    System.out.println("非法的手机号码");
}

The output is “valid phone number”.

bannerAds