gpt4 book ai didi

java - 如何从与 Java 中的某个表达式匹配的字符串中获取值?

转载 作者:太空宇宙 更新时间:2023-11-04 13:47:40 25 4
gpt4 key购买 nike

我正在开发一个表达式值读取器。在到处寻找这样的 API 但没有找到任何东西后,我决定创建自己的 API。我创建了一个名为 ExpressionMatcher 的类。它应该是这样工作的:

    private static final String TEMPLATE = "my name is {username} and i am {userage} years old";
private ExpressionMatcher expressionMatcher = new ExpressionMatcher(TEMPLATE);
...
String matias = "my name is Matias and i am 25 years old";
String fede = "my name is Federico and i am 23 years old";

Map<String, String> variables = expressionMatcher.getValuesFromString(matias);

assertEquals("Matias", variables.get("username"));

表达式匹配器的代码是这样的:

public class ExpressionMatcher {

List<String> variableNames = new ArrayList<String>();
private final Pattern expressionPattern;

public ExpressionMatcher(String template) {
// Look for variable names in the string
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher matcher = pattern.matcher(template);
while(matcher.find()) {
// Add variable names into a list
variableNames.add(matcher.group(1));
}
// replace the variable names with a new regex that will match all incoming expressions and compile a pattern
this.expressionPattern = Pattern.compile(matcher.replaceAll("(.*?)"));

}

public Map<String, String> getValuesFromString(String expression) {
Matcher matcher = this.expressionPattern.matcher(expression);
Map<String, String> variables = new HashMap<String, String>();
if(!matcher.matches()) {
return Collections.emptyMap();
} else {
int i = 0;
while(matcher.find()) {

variables.put(variables.get(i), matcher.group(1));
i++;
}
}
return variables;
}

到目前为止,我已经能够成功获取变量名称,但无法获取纯文本表达式的值。我怎样才能做到这一点?谢谢,

最佳答案

没关系,

经过更多测试后,我解决了这个问题。在 getValueFromString 方法中,我添加了以下代码:

    public Map<String, String> getValuesFromExpression(String expression) {
Matcher matcher = this.expressionPattern.matcher(expression);
Map<String, String> variables = new HashMap<String, String>();
if(!matcher.matches()) {
return Collections.emptyMap();
} else {
// Iterate over the groups
for(int i = 0; i < matcher.groupCount(); i++) {
variables.put(variableNames.get(i), matcher.group(i + 1));
}
}
return variables;
}

我希望至少这对某人有帮助。

关于java - 如何从与 Java 中的某个表达式匹配的字符串中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670030/

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