跳到主要内容

Java字符串matches()方法

matches() 方法检查字符串是否与给定的正则表达式匹配。

示例

class Main {
public static void main(String[] args) {

// 一个正则表达式模式
// 以 'J' 开头和以 'a' 结尾的四个字母的字符串
String regex = "^J..a$";

System.out.println("Java".matches(regex));

}
}

// 输出: true

matches() 的语法

字符串 matches() 方法的语法是:

string.matches(String regex)

这里,stringString 类的一个对象。

matches() 参数

matches() 方法接受单个参数。

  • regex - 一个正则表达式

matches() 返回值

  • 返回 true 如果正则表达式与字符串匹配
  • 返回 false 如果正则表达式不与字符串匹配

示例 1:Java matches()

class Main {
public static void main(String[] args) {

// 一个正则表达式模式
// 以 'a' 开头和以 '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:检查数字

// 检查字符串是否只包含数字

class Main {
public static void main(String[] args) {

// 只包含数字的搜索模式
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 正则表达式