我要用另一个子串替换String中的一组子串,例如
"^t"
与"\t"
"^="
与"\u2014"
"^+"
与"\u2013"
"^s"
与"\u00A0"
"^?"
与"."
"^#"
与"\\d"
"^$"
与"[a-zA-Z]"
所以,我试过了:
String oppip = "pippo^t^# p^+alt^shefhjkhfjkdgfkagfafdjgbcnbch^";
Map<String,String> tokens = new HashMap<String,String>();
tokens.put("^t", "\t");
tokens.put("^=", "\u2014");
tokens.put("^+", "\u2013");
tokens.put("^s", "\u00A0");
tokens.put("^?", ".");
tokens.put("^#", "\\d");
tokens.put("^$", "[a-zA-Z]");
String regexp = "^t|^=|^+|^s|^?|^#|^$";
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(oppip);
while (m.find())
m.appendReplacement(sb, tokens.get(m.group()));
m.appendTail(sb);
System.out.println(sb.toString());
但它不起作用。 tokens.get(m.group())
抛出异常。
知道为什么吗?
答案 0 :(得分:6)
您不必使用HashMap
。考虑使用简单数组和循环:
String oppip = "pippo^t^# p^+alt^shefhjkhfjkdgfkagfafdjgbcnbch^";
String[] searchFor =
{"^t", "^=", "^+", "^s", "^?", "^#", "^$"},
replacement =
{"\\t", "\\u2014", "\\u2013", "\\u00A0", ".", "\\d", "[a-zA-Z]"};
for (int i = 0; i < searchFor.length; i++)
oppip = oppip.replace(searchFor[i], replacement[i]);
// Print the result.
System.out.println(oppip);
为了完整性,您可以使用二维数组来实现类似的方法:
String oppip = "pippo^t^# p^+alt^shefhjkhfjkdgfkagfafdjgbcnbch^";
String[][] tasks =
{
{"^t", "\\t"},
{"^=", "\\u2014"},
{"^+", "\\u2013"},
{"^s", "\\u00A0"},
{"^?", "."},
{"^#", "\\d"},
{"^$", "[a-zA-Z]"}
};
for (String[] replacement : tasks)
oppip = oppip.replace(replacement[0], replacement[1]);
// Print the result.
System.out.println(oppip);
答案 1 :(得分:5)
在正则表达式中,^
表示&#34;文本开头&#34; (或&#34; not&#34;在字符类中作为否定)。你必须在它之前加一个反斜杠,它在java String中变成两个反斜杠。
String regexp = "\\^[t=+s?#$]";
我进一步减少了它。