2013-04-04 58 views
4

我想使用java正則表達式來輸入以下輸入。我相信我的表達應該貪婪地匹配下面的程序中的外部「exec」標記。在正則表達式貪婪匹配(java)

@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")] 

任何人都可以請幫助我理解我要去哪裏錯了嗎?

回答

3

默認情況下,點符號.與換行符不匹配。這裏,在這種情況下,「exec」模式只有在它出現在同一行上時纔會匹配。

您可以使用Pattern.DOTALL,以允許匹配要在換行符完成:

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

或者(?s)可以指定,這相當於:

Pattern.compile("(?s)exec\\s*\\(.*\\)"); 
+0

非常感謝你:) – qwerty 2013-04-04 02:32:34

+0

'默認情況下,Java正則表達式模式與換行符不匹配您可能是指'.'默認情況下不匹配新行。 – nhahtdh 2013-04-04 07:10:01