一、采用String类的match匹配
代码:
public static void main(String[] args) {
//目标字符串str;
String str = "123456";
//自定义的正则表达式,用于匹配str的;
String regex = "^\\d+$";
//字符串str对象的 Boolean matchers(String regex)的方法,检查是否匹配上。
boolean matches = str.matches(regex);
System.out.println(matches);
}
二、与Pattern,Macher一起使用
代码:
//目标字符串str;
String str = "123456";
//自定义的正则表达式,用于匹配str的;
String regex = "^\\d+$";
//通过Pattern类的 Pattern complile(String regex)方法得到解析器pattern对象
Pattern pattern = Pattern.compile(regex);
//也可以使用Pattern complile(String regex,int flags)方法得到忽略大小写的解析器对象。
Pattern pattern2 = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
//通过Pattern类的 matcher(要传入匹配的字符串str)得到Matcher对象
Matcher matcher = pattern.matcher(str);
//通过matcher的matches()方法,返回是否匹配。
boolean matches = matcher.matches();
}
三、regex的写法
需要用时再经行查阅!