在我的java代碼中,我希望類似於如果字符串輸入有任何提及的特殊字符,應該在前面加上\
。
特殊字符集是{+, -, &&, ||, !, (,), {, },[, ], ^, "", ~, *, ?, :, \}
。我嘗試使用inputString.replaceAll(old,new)
,但令我驚訝的是它不工作,即使我給予'舊'和'新'適當的值。
我把特殊字符放在一個字符串數組中,將它迭代到一個for循環中,檢查它是否存在於字符串中,如果是的話,input.replaceAll(":","\\:")
。但它沒有給我預期的輸出。請幫忙。當String,replaceAll失敗時用特殊字符替換特殊字符
String[] arr = { "+", "-", "&&", "||", "!", "(", ")", "{", "}",
"[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" };
for (int i = 0; i < arr.length; i++) {
System.out.println("arr[" + i + "]>>>>>>>>>>>>>>>" + arr[i]);
System.out.println(search.contains((String) arr[i])
+ "---------->" + arr[i]);
if (search.contains((String) arr[i])) {
System.out.println("..index..."+search.indexOf((String) arr[i]));
String oldString = (String) arr[i];
System.out.println("check if it has old string"
+ search.contains(oldString));
String newString = new String("\\" + arr[i]);
System.out
.println("About to replace special chars....with..."
+ newString);
search = search.replaceAll(oldString, newString);
String newSearch = new String(search.replaceAll(arr[i],
newString));
System.out
.println("Search String after replaceAll is ------------->: "
+ newSearch);
System.out.println("--------------"
+ search.replaceAll(arr[i], newString)
+ "---------------" + search);
}
}