1、匹配字符串后面跟数组取值, 例:object[1,2,3][0]; [0,1][2];[123]
^\w*\[\s*(-?\d+\s*(,\s*-?\d+\s*)*)\](\[\s*(-?\d+\s*(,\s*-?\d+\s*)*)\s*\])*
Pattern pattern = Pattern.compile("^\\w*\\[\\s*(-?\\d+\\s*(,\\s*-?\\d+\\s*)*)\\](\\[\\s*(-?\\d+\\s*(,\\s*-?\\d+\\s*)*)\\s*\\])*");
String[] strArr = {"object[1,2,3][0]", "[0,1][2]", "obj[10]", "[1]"};
for (String str : strArr) {
System.out.println(pattern.matcher(str).matches());
}
2、截取中括号里面的值
\[(.*?)\]
String[] strArr = {"object[1,2,3][0]", "[0,1][2]", "obj[10]", "[1]"};
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
for (String strKey : strArr) {
Matcher matcher = pattern.matcher(strKey);
while (matcher.find()) {
// System.out.println(matcher.group(0)); // 输出整个匹配的括号内内容
System.out.println(matcher.group(1)); // 输出括号内的具体值
}
System.out.println("----------------------------");
}
3、判断逗号分隔的数字是否全部为正整数
^\s*(\d+\s*,\s*)*\d*\s*$
String[] strArr = {"1,2,3", "0", "8,a,1", "-1,99", "1,2.3","aa"};
Pattern pattern = Pattern.compile("^\\s*(\\d+\\s*,\\s*)*\\d*\\s*$");
for (String strKey : strArr) {
Matcher matcher = pattern.matcher(strKey);
System.out.println(matcher.matches());
}