matches()
方法检查字符串是否匹配给定的正则表达式。
示例
class Main { public static void main(String[] args) { // a regex pattern for // four letter string that starts with 'J' and end with 'a' String regex = "^J..a$"; System.out.println("Java".matches(regex)); } } // Output: true
matches() 的语法
字符串
matches()
方法的语法是:
string.matches(String regex)
这里,
string 是
String
类的对象。
matches() 参数
matches()
方法接受一个参数。
matches() 返回值
返回真如果正则表达式匹配字符串 返回 false 如果正则表达式与字符串不匹配示例 1: Java 匹配()
class Main { public static void main(String[] args) { // a regex pattern for // five letter string that starts with 'a' and end with 's' String regex = "^a...s$"; System.out.println("abs".matches(regex)); // false System.out.println("alias".matches(regex)); // true System.out.println("an abacus".matches(regex)); // false System.out.println("abyss".matches(regex)); // true } }
这里,
"^a...s$"
是一个正则表达式,表示以
a 开头并以
s
<结尾的 5 个字母的字符串 代码>
。
结尾的>
示例 2: 检查数字
// check whether a string contains only numbers
class Main {
public static void main(String[] args) {
// a search pattern for only numbers
String regex = "^[0-9]+$";
System.out.println("123a".matches(regex)); // false
System.out.println("98416".matches(regex)); // true
System.out.println("98 41".matches(regex)); // false
}
}
这里,
"^[0-9]+$"
是一个正则表达式,表示只有数字。
要了解有关正则表达式的更多信息,请访问 Java 正则表达式。