我需要用hashmap中的值替换{0}。 hashmap键分别为0,1,2,3。什么是正确的选择。我觉得我们可以实现模式匹配。这个值的模式是什么?
Dear {0},
You are being contacted because the '{1}' named '{2}' has been changed by '{3}' in the Application. These changes may impact any existing reports you are using which depend upon this information. If you have not authorized these changes, please contact '{4}' or send a request to IT Support to have the changes reversed
输出:
Dear abc ,
You are being contacted because the ' Attribute' named 'prod1_group' has been changed by ' Guest ' in the Application. These changes may impact any existing reports you are using which depend upon this information. If you have not authorized these changes, please contact 'Guest' or send a request to IT Support to have the changes reversed
答案 0 :(得分:2)
您可以使用此正则表达式:
Pattern p = Pattern.compile("\\{(\\d+)}");
在matcher.group(1)
循环中使用HashMap
作为while (matcher.find()) {..}
的关键。
matcher
的位置:
Matcher matcher = p.matcher( input );
答案 1 :(得分:0)
您需要ecsape {
字符,否则您将获得PatternSyntaxException并捕获数字\\d+
。最后matcher.group(1)
将返回String,因此您需要将其强制转换为Integer
以下是示例
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Registrar {
public static void main(String[] args) {
String input = "Dear {0}, \n" +
"You are being contacted because the '{1}' named '{2}' has been changed by '{3}' in the Application. These changes may impact any existing reports you are using which depend upon this information. If you have not authorized these changes, please contact '{4}' or send a request to IT Support to have the changes reversed";
Pattern pattern = Pattern.compile("\\{(\\d+)}");
HashMap<Integer, String> map = new HashMap<>();
map.put(0, "zero");
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String val = matcher.group(1);
String group = matcher.group();
input = input.replace(group, map.get(Integer.parseInt(val)));
}
System.out.println(input);
}
}
并输出
Dear zero,
You are being contacted because the 'one' named 'two' has been changed by 'three' in the Application. These changes may impact any existing reports you are using which depend upon this information. If you have not authorized these changes, please contact 'four' or send a request to IT Support to have the changes reversed
答案 2 :(得分:0)
您可以使用\\{[0-9]{1}}
String testString = "{0}";
String myPattern = "\\{[0-9]{1}}";
Pattern pattern = Pattern.compile(myPattern);
Matcher m = pattern.matcher(testString);
if(m.matches()) {
System.out.println("Correct Value");
} else {
System.out.println("Wrong Value");
}
要从字符串匹配,请执行以下操作
String testString = "Dear {0},";
String myPattern = ".*\\{[0-9]{1}}.*";