I have tried the following logic to escape the special chars in a string and also to remove the escape chars from the escaped string.
public static void main(String a[])
{
String keyword = "otterbox 3500 series { { waterproof case \\(clear) phones";
System.out.println("INut keyword is "+keyword);
StringBuilder sb = new StringBuilder();
// * and ? is not included as they are wild card
for (int i = 0; i < keyword.length(); i++){
char c = keyword.charAt(i);
if (c == '\\' || c == '!' || c == '(' || c == ')' || c == '&' ||
c == ':' || c == '^' || c == '[' || c == ']' ||
c == '-' || c == '{' || c == '}' ||
c == '~'){
sb.append('\\');
}
sb.append(c);
}
keyword=sb.toString();
System.out.println("Escaped keyword is "+keyword);
if(keyword.contains("\\")){
int l=0;
int l2=0;
for (int i = 0; i < keyword.length(); i++){
char c = keyword.charAt(i);
if(c=='\\')l++;
if (c == '!' || c == '(' || c == ')' || c == '&' ||
c == ':' || c == '^' || c == '[' || c == ']' || c=='-'||
c == '{' || c == '}' || c == '~' || c=='(' || c== ')'){
keyword = keyword.replaceAll("\\\\\\"+c, ""+c);
l2++;
}
}
if(l==1) keyword= keyword.replaceAll("\\\\", "");
if(l>1 && l2==1) keyword = keyword.replaceFirst("\\\\", "");
}
System.out.println("Final "+keyword);
}
I expect the final keyword to be otterbox 3500 series { { waterproof case \ (clear) phones, since i wanted to use the \ in my string. but the output is coming as "Final otterbox 3500 series { { waterproof case \ \ (clear) phones". What Am I missing here?
What about a regexp?
Prints: