Java matches()方法
matches()方法
Java中String类方法matches()可用于判断某个字符串是否参数指定的正则表达式相匹配。如果匹配,则返回true,否则返回false。matches()语法如下:
public boolean matches(String regex)
matches()参数
参数 | 描述 |
---|---|
regex | 字符串类型表示的正则表达式 |
提示:matches()方法可以通过Java的String类型对象调用,也可以使用Pattern调用,比如Pattern.matches(regex, strObj),同样可以用于判断字符串对象是否与正则表达式相匹配。
matches()返回值
boolean类型值,true或false。
matches()实例代码
下面使用不同的方法判断字符串str是否与正则表达式相匹配:
import java.util.regex.Pattern;
public class test {
public static void main(String[] args) {
String str = "Hello";
boolean t1 = str.matches("\\w+");
boolean t2 = Pattern.matches("\\w+", str);
System.out.println("t1="+t1+"; t2="+t2);
}
}
代码运行后,得到输出值为:
t1=true; t2=true
免责声明:内容仅供参考,不保证正确性。