Java matches() Method Guide

In Java, the matches() function is a method of the String class used to check if a string matches a given regular expression.

The syntax of the matches() method is as follows:

public boolean matches(String regex)

Among them, regex is a regular expression used to specify matching rules.

The matches() method returns a boolean value: true if the string matches the regular expression, and false otherwise.

Here is an example: verifying if a string is a valid phone number.

String phoneNumber = "1234567890";
boolean isValid = phoneNumber.matches("\\d{10}");
System.out.println(isValid); // 输出true

In the example above, the regular expression “\d{10}” is used to match 10 numbers (0-9). Therefore, since the string “1234567890” matches the regular expression, the value of isValid is true.

bannerAds