2010-07-24 111 views
0

我想寫一個簡單的模板引擎來解析if語句。Java語句模式匹配

<{if $value == true}> 
    say hello 
<{/if}> 

我已經寫工作代碼但是,如果我有一個文件在多個if語句我解析那麼如果只抓取了第一個和最後的if語句。例如。不僅僅是返回say hello

say hello 
<{/if}> 
... 
<{if $value2 == true}> 
    say hello 

相反:

<{if $value1 == true}> 
    say hello 
<{/if}> 
... 
<{if $value2 == true}> 
    say hello 
<{/if}> 
... 

的代碼分析和回報。

感謝您的幫助提前代碼如下:

public class Templates { 

     private static String escape(String value) { 
      return value.replaceAll("\\$", "\\\\\\$"); 
     } 

     public static String load(String name) { 
      return load(name, null); 
     } 

     public static String load(String name, Map<String, String> parse) { 

      String page = new Resources().getTextResource("lib/tpl/" + name); 

      if (page == null) { 
       return "The template, " + name + " was NOT FOUND."; 
      } 

      if (parse != null) { 
       Iterator it = parse.entrySet().iterator(); 

       while (it.hasNext()) { 

        Map.Entry entry = (Map.Entry) it.next(); 
        String key = (String) entry.getKey(); 
        String value = (String) entry.getValue(); 

        value = escape(value); // Prevents java exception. Can't deal with $ 

        page = page.replaceAll("\\<\\{\\$" + key + "\\}\\>", value); 


       } 

       Pattern ptrn = Pattern.compile("\\<\\{if \\$([a-z]+)\\s*(==|!=|eq|neq|or|and)\\s*(\\w+)\\}\\>(\\p{ASCII}+)\\<\\{/if\\}\\>"); 

       Matcher mtch = ptrn.matcher(page); 

       System.out.println("\n\n\n"); 

       while(mtch.find()) { 

        System.out.println("Key is: " + mtch.group(1)); 
        //System.out.println("Key: " + dateMatcher.group(2)); 
        System.out.println("Value is: " + mtch.group(3)); 
        System.out.println("Data is: " + mtch.group(4)); 

        if(parse.get(mtch.group(1)).equals(mtch.group(3))) { 
         System.out.println("\n\n\nREPLACE"); 
         page = page.replaceAll(ptrn.pattern(), escape(mtch.group(4))); 
        } else { 
         //dateMatcher.appendReplacement(page, ""); 
         System.out.println("\n\n\nREMOVE - " + ptrn.pattern()); 
         page = page.replaceAll(ptrn.pattern(), ""); 
        } 

       } 

       System.out.println("\n\n\n"); 


      } 
      return page; 


} 
} 

回答

2

這可能是由於貪婪的本性。

試試這個,

(\\p{ASCII}+?),而不是(\\p{ASCII}+)

+0

我明白了,謝謝http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/ util/regex/Pattern.html – 2010-07-24 09:58:26

+2

這是一個古老的頁面(1.4.x)。以下是當前版本:http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html – 2010-07-24 12:18:23

+0

請注意,如果嵌套了if語句,則不能使用正則表達式來解析模板。 – Kwebble 2010-07-24 15:36:14