java - 使用正则表达式解析数组语法

标签 java regex arrays text-parsing

我认为我要问的问题要么非常微不足道,要么已经被问过,但我很难找到答案。

我们需要捕获给定字符串中括号之间的内部数字字符。

给定字符串

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/

相关文章:

java - Java 中的点对点电子表格应用程序

java - Verticle 核心上的多个实例

java - 从字符串中删除子字符串

regex - 匹配 *.ts 但不匹配 *.d.ts 的 Webpack 正则表达式测试

regex - R正则表达式在字符串之后/之前提取数字

c++ - 迭代器问题

javascript - 为什么 JavaScript 有以下几种连线行为?

java - 为 JPanels 创建垂直滚动面板

java - 在正则表达式世界中什么是 flavor ,Java 使用哪种 flavor ?

javascript - 将无限数量的参数传递给 sort() 函数