日期:2014-05-20  浏览次数:20779 次

请教高手: 关于正则表达式,转义字符和json

 使用流输出json数据,最后转成字符串: 结果打印出来成这样:

StringBuffer sb = new StringBuffer();
sb.append(jsonUtil.list2jsonNoSet(contentList));

getResponse().setContentType("text/html; charset=UTF-8"); //输出json
getResponse().getWriter().print(sb.toString());
//这里的红色我在内存里看到确实有\/的非法字符串...

{"imgListNavi":[{"bigImg":"http:\/\/c2.cmvideo.cn\/sup\/publish\/clt\/image\/10\/14\/119.png","channelId":"70314","haveData":"false","name":"推荐","smallImg":"http:\/\/c2.cmvideo.cn\/sup\/publish\/clt\/image\/10\/14\/113.png","urlpath":"http:\/\/c2.cmvideo.cn\/sup\/data\/clt\/v2\/listNav.jsp?channelId=70314"},{"bigImg":"http:\/\/c2.cmvideo.cn\/sup\/publish\/clt\/image\/10\/14

想用正则表达式把里面的 \/给去掉,结果一写成String str = "http:\/\/c2.cmvideo.cn"; 就会提示非法字符串,可是这样的字符串在内存中确实存在,搞了一天了。。。。。 求助达人怎么去掉字符串中的"\/" 将其换成"\\"...

------解决方案--------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegExp {
public static void main(String[] args) {
String str = "http:\\/\\/c2.cmvideo.cn";
Pattern p = Pattern.compile("\\\\/");
Matcher m = p.matcher(str);
StringBuffer buf = new StringBuffer();
while(m.find()){
m.appendReplacement(buf, "\\\\");
}
m.appendTail(buf);
System.out.println(buf);
}
}

------解决方案--------------------
Java code
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegExp {    
    public static void main(String[] args) {        
        String str = "http:\\/\\/c2.cmvideo.cn";         
        Pattern p = Pattern.compile("\\\\/");
        Matcher m = p.matcher(str);
        StringBuffer buf = new StringBuffer();
        while(m.find()){
            m.appendReplacement(buf, "\\\\");
        }
        m.appendTail(buf);
        System.out.println(buf);
    }
}

------解决方案--------------------
Java code

public class Test{
    public static void main(String[] args){
        String str = "http:\\/\\/c2.cmvideo.cn"; 
        str = str.replaceAll("\\\\","");
        System.out.println(str);
    }
}