Java String matches()

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)

这里,stringString类的一个对象


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]+$" 是一个正则表达式,表示仅包含数字。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战