Removing escape characters

2019-09-04 07:20发布

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?

1条回答
SAY GOODBYE
2楼-- · 2019-09-04 07:45

What about a regexp?

String keyword = "e!s { { wat(erpr)o}o^f ca]se \\c(lear) pho][nes &: hee-l~o";
String escaped = keyword.replaceAll("([{}()\\[\\]\\\\!&:^~-])", "\\\\$1");
String unescaped = escaped.replaceAll("\\\\([{}()\\[\\]\\\\!&:^~-])", "$1");
System.out.println(keyword);
System.out.println(escaped);
System.out.println(unescaped);

Prints:

e!s { { wat(erpr)o}o^f ca]se \c(lear) pho][nes &: hee-l~o
e\!s \{ \{ wat\(erpr\)o\}o\^f ca\]se \\c\(lear\) pho\]\[nes \&\: hee\-l\~o
e!s { { wat(erpr)o}o^f ca]se \c(lear) pho][nes &: hee-l~o
查看更多
登录 后发表回答