String类的matches方法
String类里的matches方法能匹配全字符串,而不能匹配字符串中的一部分,(这个地方好坑,一次项目中在这里耗时很长)
String str = "my phone is :13376543489.";
System.out.println(str.matches("[0-9]*"));
str = "13376543489";
System.out.println(str.matches("[0-9]*"));
运行结果:
String类中contains方法则可以检查字符串中的子字符串,但不能使用正则表达式。若存在该子字符串则返回true,否则返回false。
String str = "my phone is :/13376543489/.";
System.out.println(str.contains("is "));
System.out.println(str.contains(":"));
System.out.println(str.contains("my phone"));
System.out.println(str.contains("myphone"));
System.out.println(str.contains("/[0-9]*/"));
结果为:
Pattern和Matcher类
注意: 调用Matcher类的group方法时一定要先调用find()方法,否则会报错。
Pattern pattern = Pattern.compile("/[0-9]*/");
Matcher matcher = pattern.matcher("my phone is :/13376543489/.");
if (matcher.find()) {
System.out.println(matcher.group());
}
运行结果为: