java 正则
簡單示例:
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
總結
- 上一篇: python-opencv-视频的简单合
- 下一篇: 功能④ 小程序常用API