最近在处理数据的时候,需要对数据进行验证,在这里就用到了正则表达式来匹配数据格式。因此,总结了一些java中正则的使用。
1、详解Pattern类和Matcher类
java正则表达式通过java.util.regex包下的Pattern类与Matcher类实现。Pattern类用于创建一个正则表达式,也可以说创建一个匹配模式,它的构造方法是私有的,不可以直接创建,但可以通过Pattern.complie(String regex)简单工厂方法创建一个正则表达式。
2、代码
public class Test {
public static void main(String[] args) {
// //1、Pattern.split(CharSequence input)
// //用于分隔字符串
// Pattern p = Pattern.compile("\\d+");
// String[] str = p.split("123:456:678.789");
// //结果:str[0]="123:" str[1]="456:" str[2]="678.789"
//
// //2、Pattern.matcher(String regex,CharSequence input)是一个静态方法,用于快速匹配字符串,该方法适合用于只匹配一次,且匹配全部字符串.
// Pattern.matches("\\d+","2223");//返回true
// Pattern.matches("\\d+","2223aa");//返回false,需要匹配到所有字符串才能返回true,这里aa不能匹配到
// Pattern.matches("\\d+","22bb23");//返回false,需要匹配到所有字符串才能返回true,这里bb不能匹配到
// //3、Pattern.matches(CharSequence input)、
// //判断整个输入字符串是否符合匹配正则表达式,
// //起始处开始匹配
// Pattern p = Pattern.compile("\\d+");
// Matcher m = p.matcher("22bb23");
// m.matches();//返回false,因为bb不能被\d+匹配,导致整个字符串匹配未成功.
// Matcher m2=p.matcher("2223");
// m2.matches();//返回true,因为\d+匹配到了整个字符串
// //4、Matcher.lookingAt()
// //判断该字符串(不是整个字符串)的部分是否能够匹配,对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
// //起始处开始匹配
// Pattern p = Pattern.compile("\\d+");
// Matcher m = p.matcher("22bb23");
// m.lookingAt();//返回true,因为\d+匹配到了前面的22
// Matcher m2=p.matcher("aa2223");
// m2.lookingAt();//返回false,因为\d+不能匹配前面的aa
// //5、Matcher.find()
// //尝试查找与该模式匹配的输入序列的下一个子序列
// //对字符串进行匹配,匹配到的字符串可以在任何位置
// Pattern p=Pattern.compile("\\d+");
// Matcher m=p.matcher("22bb23");
// m.find();//返回true
// Matcher m2=p.matcher("aa2223");
// m2.find();//返回true
// Matcher m3=p.matcher("aa2223bb");
// m3.find();//返回true
// Matcher m4=p.matcher("aabb");
// m4.find();//返回false.
// //6、Mathcer.start()/ Matcher.end()/ Matcher.group()
// // 当使用matches(),lookingAt(),find()执行匹配操作后,就可以利用以上三个方法得到更详细的信息.
// // start()返回匹配到的子字符串在字符串中的索引位置.
// // end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
// // group()返回匹配到的子字符串
// Pattern p = Pattern.compile("\\d+");
// Matcher m = p.matcher("aaa2223bb");
// m.find();//匹配2223
// m.start();//返回3
// m.end();//返回7,返回的是2223后的索引号
// m.group();//返回2223
//
// Matcher m2 = p.matcher("2223bb");
// m.lookingAt(); //匹配2223
// m.start(); //返回0,由于lookingAt()只能匹配前面的字符串,所以当使用lookingAt()匹配时,start()方法总是返回0
// m.end(); //返回4
// m.group(); //返回2223
//
// Matcher m3 = p.matcher("2223bb");
// m.matches(); //匹配整个字符串
// m.start(); //返回0,原因相信大家也清楚了
// m.end(); //返回6,原因相信大家也清楚了,因为matches()需要匹配所有字符串
// m.group(); //返回2223bb
// //7、整合
// Pattern p=Pattern.compile("([a-z]+)(\\d+)");
// Matcher m=p.matcher("aaa2223bb");
// m.find(); //匹配aaa2223
// m.groupCount(); //返回2,因为有2组
// m.start(1); //返回0 返回第一组匹配到的子字符串在字符串中的索引号
// m.start(2); //返回3
// m.end(1); //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置.
// m.end(2); //返回7
// m.group(1); //返回aaa,返回第一组匹配到的子字符串
// m.group(2); //返回2223,返回第二组匹配到的子字符串
}
}
本文介绍了Java中正则表达式的应用,通过Pattern和Matcher类完成数据格式验证。包括分隔字符串、匹配字符串、查找子序列等操作,并详细解释了各种方法的使用场景。

1万+

被折叠的 条评论
为什么被折叠?



