ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java - `String matches()`方法 > 原文: [https://beginnersbook.com/2013/12/java-string-matches-method-example/](https://beginnersbook.com/2013/12/java-string-matches-method-example/) 方法`matches()`检查`String`是否与指定的[正则表达式](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum)匹配。如果`String`适合指定的正则表达式,则此方法返回`true`,否则返回`false`。以下是该方法的语法: ```java public boolean matches(String regex) ``` 它会抛出[`PatternSyntaxException`](https://docs.oracle.com/javase/7/docs/api/java/util/regex/PatternSyntaxException.html) - 如果指定的正则表达式无效。 ### 示例:`matches()`方法 在这个例子中,我们有一个`String`和三个正则表达式。我们使用`matches()`方法将正则表达式(regex)与输入`String`进行匹配。 ```java public class MatchesExample{ public static void main(String args[]){ String str = new String("Java String Methods"); System.out.print("Regex: (.*)String(.*) matches string? " ); System.out.println(str.matches("(.*)String(.*)")); System.out.print("Regex: (.*)Strings(.*) matches string? " ); System.out.println(str.matches("(.*)Strings(.*)")); System.out.print("Regex: (.*)Methods matches string? " ); System.out.println(str.matches("(.*)Methods")); } } ``` 输出: ```java Regex: (.*)String(.*) matches string? true Regex: (.*)Strings(.*) matches string? false Regex: (.*)Methods matches string? true ```