{0}的Java模式匹配
我需要用hashmap中的值替换{0}。hashmap键分别为0,1,2,3。我觉得我们可以实现模式匹配器。这个值的模式是什么{0}的Java模式匹配,java,regex,Java,Regex,我需要用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 up
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
您可以使用此正则表达式:
Pattern p = Pattern.compile("\\{(\\d+)}");
并使用matcher.group(1)
作为while(matcher.find()){..}
循环中HashMap
的键
其中,matcher
是:
Matcher matcher = p.matcher( input );
您需要ecsape
{
字符,否则您将获得PatternSyntaxException,为了捕获数字\\d+
。最后匹配器。组(1)
将返回字符串,因此您需要将其强制转换为整数
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);
}
}
你可以用\{[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}}.*";
PatternSyntaxException将失败,您必须转义{字符。感谢@iMmo:I之前有\{
和\}
,但后来它在regex101站点上正常工作,所以我将其删除:)我看到了,但regex101不支持java,顺便说一句,不需要转义:)
String testString = "Dear {0},";
String myPattern = ".*\\{[0-9]{1}}.*";