【问题标题】:Parsing array syntax using regex使用正则表达式解析数组语法
【发布时间】: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


【解决方案1】:

为了捕获每个数字,您需要更改您的正则表达式,以便 (a) 捕获单个数字并且 (b) 不会锚定到 - 因此受 - 字符串的任何其他部分 ("^ \w*?" 将其锚定到字符串的开头)。然后你可以遍历它们:

Matcher mtchr = Pattern.compile("\\[(\\d+)\\]").matcher(arrayAsStr);
while(mtchr.find())  {
   System.out.print(mtchr.group(1) + " ");
}

输出:

0 9 4 45 1

【讨论】:

  • 在我接受你的答案之前,这是正确的并且确实有效......我想知道如何确保单词和第一个括号之间没有空格,最后一个括号和线的结尾......那并不重要......但会在我的场景中增加极端价值。顺便说一句,循环非常有价值。
  • 首先将整行与“^\\w+(?:\\[(\\d+)\\])+$”匹配。找到时(当“mtchr.matches()”为真时)按照我的回答运行上述内容。
猜你喜欢
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2020-01-13
  • 1970-01-01
  • 2021-05-21
  • 2011-08-10
  • 2015-07-08
相关资源
最近更新 更多