Java.lang.String.matches() 方法
描述
java.lang.String.matches() 方法告诉我们这个字符串是否匹配给定的正则表达式。
声明
以下是 java.lang.String.matches() 方法的声明。
public boolean matches(String regex)
参数
regex − 这是这个字符串要匹配的正则表达式。
返回值
当且仅当此字符串与给定的正则表达式匹配时,此方法才返回 true。
异常
PatternSyntaxException − 如果正则表达式的语法无效。
示例
下面的例子展示了 java.lang.String.matches() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "learning";
boolean retval = str1.matches(str2);
// method gets different values therefore it returns false
System.out.println("Value returned = " + retval);
retval = str2.matches("learning");
// method gets same values therefore it returns true
System.out.println("Value returned = " + retval);
retval = str1.matches("tuts");
// method gets different values therefore it returns false
System.out.println("Value returned = " + retval);
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Value returned = false Value returned = true Value returned = false

