【发布时间】:2021-06-19 22:36:33
【问题描述】:
给定两个字符串
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
我引用了this answer on 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 但我无法获得任何符合我期望的方法。
【问题讨论】:
-
你能用docs.oracle.com/javase/7/docs/api/java/text/…吗?它为参数提供了一个 Object[] 数组。
-
String.format()是否符合您的要求? -
@FaltFe OP 正在寻找“反向”格式化程序 - 即解析 args。
-
Java 正则表达式/模式匹配可以做到这一点。 stackoverflow.com/questions/4662215/…
-
@JayC667 OP 正在寻找处理极端情况的成熟 解决方案。正则表达式不适合这种情况,因为所说的极端情况可能很难/不可能处理。
标签: java regex placeholder apache-commons messageformat