2014-10-29 132 views
2

我有下面的代碼如何獲得在StringTemplate的V4屬性

String templateString = "Some Text $attribute1$ more text $attribute2$ more text"; 
ST stringTemplate = new ST(templateString ,'$','$');` 

我怎麼能遍歷所有的屬性即ATTRIBUTE1,attribute2等? 我想獲取模板中的所有屬性列表。

+0

你確定這是一個有效的'ST'?你可以使用它嗎? – 2014-10-29 10:54:33

+0

是的,它是有效的ST。我可以使用add()來替換屬性值,但無法獲取屬性列表。 – user3751014 2014-10-29 10:57:51

回答

0

在常規使用只是像這樣的正則表達式,它似乎做什麼,我需要現在

List<String> extractTemplateVariables(String statement) { 
    Pattern pattern = Pattern.compile(/\$(\w*)\$/); 
    def List<String> runTimeParms = [] 
    def matcher = pattern.matcher(statement) 

    while (matcher.find()) { 
     runTimeParms << matcher.group(1) 

    } 
    runTimeParms.removeAll(Collections.singleton(null)); 
    runTimeParms.unique(false) 

}

但有人告訴我正確的方法是檢查AST東西像這樣:

final int ID = 25 
    char delimiter = '$' 
    ST st = new org.stringtemplate.v4.ST(statement, delimiter, delimiter); 

    def dataFieldNames = [] 
    def t = st.getAttributes() 
    st.impl.ast.getChildren().each { 

     if (it != null) { 
      CommonTree child = it as CommonTree 
      if (child.toString().equals("EXPR")) { 
       if (child.getChildCount() == 1) { 
        CommonTree expressionChild = child.getChild(0) 
        if (expressionChild.getToken().getType() == ID) { 
         dataFieldNames.add(expressionChild.toString()) 
        } else if (expressionChild.toString().equals("PROP")) { 
         if (expressionChild.getChildCount() == 2) { 
          dataFieldNames.add(
            expressionChild.getChild(0).toString() + 
              "." + 
              expressionChild.getChild(1).toString()) 
         } 
        } 

       } 
      } 
     } 
    } 

    dataFieldNames.unique(false) 

} 

但我不明白結構或我在這裏做什麼,它沒有看到任何比第一個更多。也許有人可以幫助我們找出最好的辦法是什麼