字符串处理离不开正则表达式,从jdk1.4开始,结合Pattern和Matcher即可实现正则处理,
下面列举一些利用java处理字符串的示例:
- 判断字符串中是否包含index_xxx这样的数据(xxx只能是数字和字母)
部分匹配
Pattern pattern = Pattern.compile("index_\\w+");
Matcher matcher = pattern.matcher("100+index_a2bc1*200");
System.out.println(matcher.find());
全文匹配
Pattern pattern = Pattern.compile(".+index_\\w+.+");
Matcher matcher = pattern.matcher("100+index_a2bc1*200");
System.out.println(matcher.matches()); #true
System.out.println(Pattern.matches("index_\\w_", "100+index_a2bc1*200")); #false
2.查询形式为:index_xxx的全部字符串(xxx只能是数字和字母)
Pattern pattern = Pattern.compile("index_\\w+");
Matcher matcher = pattern.matcher("100+index_a2bc1*200+index_aka21*(index_kab21-3023)");
while(matcher.find()) {
System.out.println(matcher.group());
}
结果:
index_a2bc1
index_aka21
index_kab21
3.查询index_xxx后的xxx字符串
Pattern pattern = Pattern.compile("index_(\\w+)");
Matcher matcher = pattern.matcher("100+index_a2bc1*200+index_aka21*(index_kab21-3023)");
while(matcher.find()) {
System.out.println(matcher.group());
}
结果:
a2bc1
aka21
kab21
5.分析以下日志,截取日期,用户,操作内容
2018-03-11 10:11:02.199 user:张三 operation:login
2018-03-12 10:11:02.199 user:李四 operation:login
2018-03-13 10:11:02.199 user:张三 operation:edit_info
2018-03-14 10:11:02.199 user:张三 operation:exit
实现:
String data = "2018-03-11 10:11:02.199 user:张三 operation:login \n" +
"2018-03-12 10:11:02.199 user:李四 operation:login \n" +
"2018-03-13 10:11:02.199 user:张三 operation:edit_info \n" +
"2018-03-14 10:11:02.199 user:张三 operation:exit";
Pattern pattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}).* user:(.*) operation:(.*)");
Matcher matcher = pattern.matcher(data);
while(matcher.find()) {
System.out.print(matcher.group(1)); #对应第一个分组
System.out.print(matcher.group(2)); #对应第二个分组
System.out.print(matcher.group(3)); #对应第三个分组
System.out.println();
}
结果:
2018-03-11张三login
2018-03-12李四login
2018-03-13张三edit_info
2018-03-14张三exit
网友评论