Java String Match()方法检查字符串是否与给定的正则表达式匹配。
字符串matches()方法的语法为:
string.matches(String regex)
在这里,string是String类的一个对象。
regex - 正则表达式
如果正则表达式与字符串匹配,则返回true
如果正则表达式与字符串不匹配,则返回false
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和结尾的5个字母的字符串s。
//检查字符串是否只包含数字
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]+$"是一个正则表达式,仅表示数字。