简单示例:
String str = "111"; String pattern = "^[0-9]*$"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(str); System.out.println(m.matches());
复杂点的示例:
String a_text = "10. mysql json 使用 类型 查询 函数(54165)";
Pattern pattern = Pattern.compile("^\\d+\\.\\s.+\\(\\d+\\)$");// 匹配 1. js 判断字符串中是否包含某个字符串(633291)
Matcher matcher = pattern.matcher(a_text);
if (matcher.find()) {
String text = matcher.group();
System.out.println(text);
int title_start = 0, title_end = 0;
Pattern pattern2 = Pattern.compile("^\\d+\\.\\s");// 匹配 1.
Matcher matcher2 = pattern2.matcher(a_text);
if (matcher2.find()) {
int start = matcher2.start();
int end = matcher2.end();
title_start = end;
String top = a_text.substring(start, end - 2);
System.out.println(top);
}
Pattern pattern3 = Pattern.compile("\\(\\d+\\)$");// 匹配 633291)
Matcher matcher3 = pattern3.matcher(a_text);
if (matcher3.find()) {
int start = matcher3.start();
int end = matcher3.end();
title_end = start;
String read_count = a_text.substring(start + 1, end - 1);
System.out.println(read_count);
}
String title = a_text.substring(title_start, title_end);
System.out.println(title);
捕获组示例:
String a_text = "10. mysql json 使用 类型 查询 函数(54165)";
Pattern pattern = Pattern.compile("(^\\d+)\\.\\s(.+)\\((\\d+)\\)$");
Matcher matcher = pattern.matcher(a_text);
if (matcher.find()) {
System.out.println("Found value: " + matcher.group(0) );//Found value: 10. mysql json 使用 类型 查询 函数(54170)
System.out.println("Found value: " + matcher.group(1) );//Found value: 10
System.out.println("Found value: " + matcher.group(2) );//Found value: mysql json 使用 类型 查询 函数
System.out.println("Found value: " + matcher.group(3) );//Found value: 54170
}
正则表达式-教程:https://www.runoob.com/regexp/regexp-tutorial.html
java正则表达式-教程:https://www.runoob.com/java/java-regular-expressions.html
正则表达式在线测试:https://c.runoob.com/front-end/854
来源:https://www.cnblogs.com/ooo0/p/12035659.html