我正在尝试使用Java正则表达式标记以下输入。我相信我的表情应该贪心地匹配下面程序中的外部“exec”标记。

@Test
    public void test(){
        String s = "exec(\n" +
                "    \"command #1\"\n" +
                "    ,\"* * * * *\" //cron string\n" +
                "    ,\"false\" eq exec(\"command #3\")) //condition\n" +
                ")\n" +
                "\n" +  //split here
                "exec(\n" +
                "    \"command #2\" \n" +
                "    ,\"exec(\"command #4\") //condition\n" +
                ");";
        List<String> matches = new ArrayList<String>();
        Pattern pattern = Pattern.compile("exec\\s*\\(.*\\)");
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            matches.add(matcher.group());
        }
        System.out.println(matches);
    }

我期望输出为
[exec(
    "command #1"
    ,"* * * * *" //cron string
    ,"false" eq exec("command #3")) //condition
),exec(
    "command #2"
    ,"exec("command #4") //condition
);]

但是得到
[exec("command #3")), exec("command #4")]

谁能帮我了解我要去哪里错了?

最佳答案

默认情况下,点字符.与换行符不匹配。在这种情况下,“exec”模式只有在同一行上才会匹配。

您可以使用Pattern.DOTALL允许对换行符进行匹配:

Pattern.compile("exec\\s*\\(.*\\)", Pattern.DOTALL);

或者,可以指定(?s),它等效:
Pattern.compile("(?s)exec\\s*\\(.*\\)");

07-26 06:17
查看更多