2014-10-29 44 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) 

} 

但我不明白结构或我在这里做什么,它没有看到任何比第一个更多。也许有人可以帮助我们找出最好的办法是什么