求一个正则表达式:要求把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"}]感谢正则达人了~~~~
原字符串:
[{"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"}]感谢正则达人了~~~~
str = str.replace(/"(\w+)"(\s*:\s*)/g, "$1$2");推荐正则调试工具:http://www.renrousousuo.com/tools/regex_debug.html
{"{\"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"}}
Pattern p = Pattern.compile("\"(\\w+)\"(\\s*:\\s*)");
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);
}
}