寻求REGEX的匹配组与选择关闭字符串

问题描述 投票:0回答:2

我有一个由多个 "new Array(...) "子串组成的字符串。每个数组都以") "结尾,除了最后一个数组,它以")) "结尾。

一个示例Strong看起来是这样的。

String text="root(new Array(\"Field1\", \"Field2\"), new Array(new Array(\"myArray1F1 (St.)\", \"myArray1F2\"),new Array(\"myArray2F1\", \"myArray2F2\"),new Array(\"myArray3F1\", \"myArray3F2\")) 0, 0)";

我试了几个自己编的或在网上找到的模式。但都没有效果。我从这个模式开始尝试,但还是不明白,为什么不能用。

Pattern.compile("(new Array\\(\".*(\\),|\\)\\)))");

或者

Pattern.compile("(new Array\\(\"(?!\\),|\\)\\)).*)");

这几乎是原封不动地返回整个字符串。

    @Test
    public void testMyArray() {
        Pattern arrayPattern = Pattern.compile("(new Array\\(\".*(\\),|\\)\\)))");
        String text="root(new Array(\"Field1\", \"Field2\"), new Array(new Array(\"myArray1F1 (St.)\", \"myArray1F2\"),new Array(\"myArray2F1\", \"myArray2F2\"),new Array(\"myArray3F1\", \"myArray3F2\")) 0, 0)";
        Matcher matcher = arrayPattern.matcher(text);
        while  (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }

这些是我想检测的组。

new Array("Field1", "Field2") 
new Array("myArray1F1 (St.)", "myArray1F2") 
new Array("myArray2F1", "myArray2F2") 
new Array("myArray3F1", "myArray3F2") 
java regex multiple
2个回答
0
投票

以下是我的工作原理。

/* Required imports
 * import java.util.regex.Matcher;
 * import java.util.regex.Pattern;
 */
Pattern pttrn = Pattern.compile("new Array\\(\".+?\"\\),?");
Matcher mtchr = pttrn.matcher(text);
while (mtchr.find()) {
    System.out.println(mtchr.group());
}

这个模式可以查找以 new Array( 后面是一个双引号,后面是一个或多个字符,然后是另一个双引号,后面是一个括号,也许用一个逗号结束。

注意 +? 被称为 勉强限定词? 表示正好是一个或没有。

输出是

new Array("Field1", "Field2"),
new Array("myArray1F1 (St.)", "myArray1F2"),
new Array("myArray2F1", "myArray2F2"),
new Array("myArray3F1", "myArray3F2")
© www.soinside.com 2019 - 2024. All rights reserved.