在我的 java 代码中,我想要一些类似的东西,如果一个字符串输入有任何提到的特殊字符,那应该在前面加上\
.
特殊字符集是{+, -, &&, ||, !, (, ), {, },[, ], ^, "", ~, *, ?, :, \}
. 我尝试使用inputString.replaceAll(old,new)
但令我惊讶的是它不起作用,即使我为“旧”和“新”提供了正确的值。
我将特殊字符放在一个字符串数组中,在 for 循环中对其进行迭代,检查它是否存在于字符串中,如果是,input.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);
}
}