我想打印不匹配的字符串,但結果爲空。如何打印不匹配字符串
public class Replacement {
public static void main(String[] ignored) {
String str = "aaa bbb ddd";
Map<String, String> mapping = new HashMap<>();
mapping.put("aaa", "hello");
mapping.put("bbb", "java");
mapping.put("ccc", "world");
Pattern pattern = Pattern.compile("([a-zA-Z_]+)"); // pattern compiling
Matcher matcher = pattern.matcher(str); // pattern matching
StringBuffer sb = new StringBuffer();
while(matcher.find()) { // while matcher found
String replace = mapping.get(matcher.group());
matcher.appendReplacement(sb, replace + " ");
}
matcher.appendTail(sb);
System.out.println(sb);
}
}
結果:
你好java的空//我的預期「你好java的DDDD
我需要把while(!matcher.find())
由於您在地圖上沒有鍵「dddd」,因此返回** null **是正確的。 – developer033