Java教程

Java String matches()

Java String matches()

在本教程中,我们将通过示例了解 Java String matching() 方法。
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() 返回值

返回真如果正则表达式匹配字符串 返回 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 正则表达式。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4