gpt4 book ai didi

java - 如何获取 StringTemplate v4 中的属性

转载 作者:行者123 更新时间:2023-12-02 17:11:48 25 4
gpt4 key购买 nike

我有以下代码

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

如何迭代所有属性,即 attribute1、attribute2 等?我想获取模板中的所有属性列表。

最佳答案

在 groovy 中只使用了这样的正则表达式,它似乎可以满足我现在的需要

   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 )

}

但是我不明白这个结构或者我在这里做什么,而且它看到的也只是第一个。也许有人可以帮助我们找出最好的方法是什么

关于java - 如何获取 StringTemplate v4 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26624211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com