我正在寻找一个 Java 类,它针对给定的字符串“${animal} jumped over the ${target}”。能够提取变量名称,即“动物”和“目标”。
我曾希望StrSubstitutor在 Commons Lang 中有一个方法
getVariables(String str) : List<String>
...但没有这样的运气。
是的,我可以自己写这个,但我确信一定有一个第三方库可以做到这一点。
最佳答案
如果你真的只想提取这些值并避免整个库的依赖性,你可以做一个简单的正则表达式匹配:
public List<String> getVariableNames(String source) {
List<String> vs = new ArrayList<String>();
Pattern p = Pattern.compile("\\$\\{(\\w+)\\}");
Matcher m = p.matcher(source);
while (m.find()) {
vs.add(m.group(1));
}
return vs;
}
将模式存储为成员变量将提高性能。
关于java - 如何从字符串中提取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6210127/