求一个正则表达式:要求把json串中“:”前面名称部分的双引号去掉,值中的双引号保留。如下例:
原字符串:
[{"attributes":{"id":"1"},"children":[{"attributes":{"id":"11"},"children":[],"data":"name11","state":"open"},{"attributes":{"id":"12"},"children":[],"data":"name12","state":"open"}],"data":"name1","state":"open"},{"attributes":{"id":"2"},"children":[],"data":"name2","state":"open"}]我需要的字符串:(注意“冒号”前面名称部分的引号没有了,值中的引号是保留的。
[{attributes:{id:"1"},children:[{attributes:{id:"11"},children:[],data:"name11",state:"open"},{attributes:{id:"12"},children:[],data:"name12",state:"open"}],data:"name1",state:"open"},{attributes:{id:"2"},children:[],data:"name2",state:"open"}]感谢正则达人了~~~~

解决方案 »

  1.   

    str = str.replace(/"(\w+)":/g, "$1:");
      

  2.   

    兼容一下有空格的情况:
    str = str.replace(/"(\w+)"(\s*:\s*)/g, "$1$2");推荐正则调试工具:http://www.renrousousuo.com/tools/regex_debug.html
      

  3.   

    感谢zswang如果在java服务层代码里写,应该怎么做呢?
      

  4.   

    本帖最后由 zswang 于 2010-04-28 10:46:18 编辑
      

  5.   

    如果在java服务层代码里写,应该怎么写呢?
      

  6.   

    str=str.replaceAll("\\"([^\\"]+?)\\"[:]","\\1");
      

  7.   

    不対,是 str=str.replaceAll("\\"([^\\"]+?)\\"[:]","$1");
      

  8.   

    这样写结果不正确,错误的结果是这样的:
    {"{\"attributes\":{\"id\":\"1\"},\"children\":[{\"attributes\":{\"id\":\"11\"},\"children\":[],\"data\":\"name11\",\"state\":\"open\"},{\"attributes\":{\"id\":\"12\"},\"children\":[],\"data\":\"name12\",\"state\":\"open\"}],\"data\":\"name1\",\"state\":\"open\"}":{attributes:{id:"1"},children:[{attributes:{id:"11"},children:[],data:"name11",state:"open"},{attributes:{id:"12"},children:[],data:"name12",state:"open"}],data:"name1",state:"open"},"{\"attributes\":{\"id\":\"2\"},\"children\":[],\"data\":\"name2\",\"state\":\"open\"}":{attributes:{id:"2"},children:[],data:"name2",state:"open"}}
      

  9.   

    通过了。谢谢zswang,我的代码刚才有bug。结贴
      

  10.   

    多了几个/
    Pattern p = Pattern.compile("\"(\\w+)\"(\\s*:\\s*)");
      

  11.   

    原来String就有这个方法:
    public class Main {
        public static void main(String[] args) {
            String json = "{\"name\":\"value\"}";
            String t = json.replaceAll("\"(\\w+)\"(\\s*:\\s*)", "$1$2");
            System.out.println(t);
        }
    }