删除转义字符 [英] Removing escape characters

查看:200
本文介绍了删除转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试下面的逻辑来躲避特殊字符的字符串,也从转义字符串中删除转义字符。

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


}

我希望最后的关键字是OtterBox保护3500系列{{防水套\(清)手机,因为我想用\我的字符串。但输出是未来的最终OtterBox保护3500系列{{防水套\ \(清除)手机。我在想什么吗?

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?

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

这篇关于删除转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆