我认为我要问的问题要么非常微不足道,要么已经被问过,但我很难找到答案。
我们需要捕获给定字符串中括号之间的内部数字字符。
给定字符串
StringWithMultiArrayAccess[0][9][4][45][1]
和正则表达式
^\w*?(\[(\d+)\])+?
我期望有 6 个捕获组并可以访问内部数据。 但是,我最终只捕获了捕获组 2 中的最后一个“1”字符。
如果这很重要,这是我的 java junit 测试:
@Test
public void ensureThatJsonHandlerCanHandleNestedArrays(){
String stringWithArr = "StringWithMultiArray[0][0][4][45][1]";
Pattern pattern = Pattern.compile("^\\w*?(\\[(\\d+)\\])+?");
Matcher matcher = pattern.matcher(stringWithArr);
matcher.find();
assertTrue(matcher.matches()); //passes
System.out.println(matcher.group(2)); //prints 1 (matched from last array symbols)
assertEquals("0", matcher.group(2)); //expected but its 1 not zero
assertEquals("45", matcher.group(5)); //only 2 capture groups exist, the whole string and the 1 from the last array brackets
}
最佳答案
为了捕获每个数字,您需要更改正则表达式,以便它 (a) 捕获单个数字,并且 (b) 不锚定到(因此受到限制)字符串的任何其他部分(“^\w*?"将其锚定到字符串的开头)。然后你可以循环它们:
Matcher mtchr = Pattern.compile("\\[(\\d+)\\]").matcher(arrayAsStr);
while(mtchr.find()) {
System.out.print(mtchr.group(1) + " ");
}
输出:
0 9 4 45 1
关于java - 使用正则表达式解析数组语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730661/