删除转义字符

时间:2012-10-25 12:03:02

标签: java regex algorithm oop java-ee

我尝试了以下逻辑来转义字符串中的特殊字符,并从转义字符串中删除转义字符。

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);


}

我希望最终的关键字是otterbox 3500 series {{防水案例\(清除)手机,因为我想在我的字符串中使用\。但输出结果是“最终的otterbox 3500系列{{防水外壳\ \(清晰)手机”。我在这里失踪了什么?

1 个答案:

答案 0 :(得分:1)

正则表达式怎么样?

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);

打印:

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