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()
方法接受一个参数。
- regex - 一个正则表达式
matches() 返回值
- 返回 true,如果正则表达式匹配字符串
- 返回 false,如果正则表达式不匹配字符串
示例 1:Java matches()
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]+$"
是一个正则表达式,表示仅包含数字。