Java String matches() 方法

定义和用法

matches() 方法在字符串中搜索正则表达式的匹配项,并返回匹配项。

实例

检查字符串是否与正则表达式匹配:

String regex = "cat|dog|fish";

System.out.println("cat".matches(regex));
System.out.println("dog".matches(regex));
System.out.println("catfish".matches(regex));
System.out.println("doggy bag".matches(regex));

亲自试一试

语法

public String matches(String regex)

参数

参数 描述
regex 正则表达式。

技术细节

返回:

boolean 值:

  • 如果正则表达式与字符串完全匹配,则为 true
  • 如果不匹配字符串,则为 false