给定两个字符串
String command = "Header '{1}' has a value that ends with '{2}' (ignore case)";
String input = "Header 'some-value' has a value that ends with '123ws' (ignore case)";
我想获得价值图。
0 -> some-value
1 -> 123ws
我在 Java Comparing two strings with placeholder values 上引用了这个答案,对我的使用做了一点调整。
private static Map<Integer, Object> getUserInputMap(String command, String input) {
System.out.println("\t" + command);
System.out.println("\t" + input);
command = command.replace("(", "<");
command = command.replace(")", ">");
input = input.replace("(", "<");
input = input.replace(")", ">");
Map<Integer, Object> userInputMap = new HashMap<>();
String patternTemplate = command.replace("{0}", "(.*)");
patternTemplate = patternTemplate.replace("{1}", "(.*)");
patternTemplate = patternTemplate.replace("{2}", "(.*)");
Pattern pattern = Pattern.compile(patternTemplate);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
for (int gi = 1; gi <= matcher.groupCount(); gi++) {
String uin = matcher.group(gi);
uin = uin.replace("<", "(");
uin = uin.replace(">", ")");
userInputMap.put(gi - 1, uin);
}
}
return userInputMap;
}
但是,可能有很多极端情况。我对我的解决方案的担心是我可能会错过一个角落案例,然后是生产错误。
是否有围绕此编写的成熟库?我正在检查 MessageFormat/StrSubstitutor 但我无法获得任何符合我期望的方法。