在我的java代码中,我想要的是,如果字符串输入有任何提到的特殊字符,那么前面应该有一个\
。
特殊字符集为{+, -, &&, ||, !, (, ), {, },[, ], ^, "", ~, *, ?, :, \}
。我尝试使用inputString.replaceAll(old,new)
,但令我惊讶的是它不起作用,即使我为'old'和'new'提供了正确的值。
我将特殊字符放在一个String数组中,在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);
}
}
答案 0 :(得分:0)
你需要首先逃避单个反斜杠(在逃避其他任何事情之前),或者双重逃避一些反斜杠。
示例:1+1
将+
替换为\+
=&gt; 1\+1
将\
替换为\\
=&gt; 1\\+1
(哎呀!)
答案 1 :(得分:0)
不确定您是否有答案。今天我也在努力。我修改了你的代码以使用我的解决方案。希望它对你有所帮助。
String search = "$&+";
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.replace("\\" + oldString, newString);
String newSearch = new String(search);
System.out
.println("Search String after replaceAll is ------------->: "
+ newSearch);
}
}