簡體   English   中英

使用正則表達式解析數組語法

[英]Parsing array syntax using regex

我認為我要問的是非常瑣碎的或已經問過的,但是我很難找到答案。

我們需要捕獲給定字符串中括號之間的內部數字字符。

所以給定字符串

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM