找到所有匹配到的子串
String exp = "(.*?)\\((.*?)\\),"; Pattern pattern = Pattern.compile(exp); String a = "Mary(12),Tom(20),Jhon(32),"; Matcher matcher = pattern.matcher(a); while (matcher.find()) { // 打印子串中的所有内容:0是完整子串。n要取等 int n = matcher.groupCount(); System.out.print(n); for (int i = 0; i <= n; i++) { System.out.print(" " + matcher.group(i)); } System.out.println(); }group()方法如果里面填写的是数字,那么返回的就是括号里面的内容 如果里面是名字,那么返回的就是尖括号里面的内容 所以,以数字取本质上和用名字取是一样的 java 获取正则表达式自身里面的变量
private static String[] getAllExpName(String exp) { String reg = "<(\\w+)>"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(exp); String[] ans = new String[]; int cnt = 0; while (matcher.find()){ ans[cnt++] = matcher.group(); } return ans; }