【发布时间】:2014-05-08 23:12:59
【问题描述】:
我认为我要问的问题要么很琐碎,要么已经问过了,但我很难找到答案。
我们需要捕获给定字符串中括号之间的内部数字字符。
所以给定字符串
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
}
【问题讨论】:
-
数字前面的字符串真的很重要吗?当您重复捕获组时,只有最后一次捕获将保留在捕获的组中。
标签: java regex arrays text-parsing