2016-12-31 211 views
3

我有一个很长的字符串,看起来像Java的正则表达式字符串转换为有效的JSON字符串

{abc:\"def\", ghi:\"jkl\"} 

我想将其转换为有效的JSON字符串像

{\"abc\":\"def\", \"ghi\":\"jkl\"} 

我开始看对字符串对象的replaceAll(String regex, String replacement)方法,但我努力寻找它的正确的正则表达式。

有人可以帮助我这个。

+2

另一种方法是使用宽松解析器解析它,例如, Gson有['setLenient()'](https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/stream/JsonReader.html#setLenient-boolean -) 方法。然后将其写回为有效的JSON。 – Andreas

+0

你正在使用哪个json依赖关系?更好的选择是根据正确的格式生成它,不管它是客户端还是服务器端 –

+0

您可以尝试通过搜索一系列标识符字符后跟':'来进行替换,但如果冒号存在,则可能会导致失败在任何值字符串中。其他可能会击败你的东西是其中一个值中的引号。有可能想出一个处理所有事情的复杂正则表达式,但在这种情况下,最好编写自己的词法分析器来处理输入中的令牌(比如'{',':',',',标识符,字符串文字)并从中工作。无论如何,过于复杂的正则表达式是不可读的,并且容易出错。 – ajb

回答

0

我必须假定“键”和“值”只包含 “单词字符”(\ w),并且它们中没有空格。

这是我的程序。另请参阅在线评论:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class RegexJson { 

    public static void main(String[] args) { 
     /* 
     * Note that the input string, when expressed in a Java program, need escape 
     * for backslash (\) and double quote ("). If you read directly 
     * from a file then these escapes are not needed 
     */ 
     String input = "{abc:\\\"def\\\", ghi:\\\"jkl\\\"}"; 

     // regex for one pair of key-value pair. Eg: abc:\"edf\" 
     String keyValueRegex = "(?<key>\\w+):(?<value>\\\\\\\"\\w+\\\\\\\")"; 
     // regex for a list of key-value pair, separated by a comma (,) and a space () 
     String pairsRegex = "(?<pairs>(,*\\s*"+keyValueRegex+")+)"; 
     // regex include the open and closing braces ({}) 
     String regex   = "\\{"+pairsRegex+"\\}"; 

     StringBuilder sb = new StringBuilder(); 

     sb.append("{"); 
     Pattern p1 = Pattern.compile(regex); 
     Matcher m1 = p1.matcher(input); 
     while (m1.find()) { 
      String pairs = m1.group("pairs"); 
      Pattern p2 = Pattern.compile(keyValueRegex); 
      Matcher m2 = p2.matcher(pairs); 
      String comma = "";  // first time special 
      while (m2.find()) { 
       String key  = m2.group("key"); 
       String value = m2.group("value"); 
       sb.append(String.format(comma + "\\\"%s\\\":%s", key, value)); 
       comma = ", ";  // second time and onwards 
      } 
     } 
     sb.append("}"); 

     System.out.println("input is: " + input); 
     System.out.println(sb.toString()); 
    } 

} 

打印出这个计划的是:

input is: {abc:\"def\", ghi:\"jkl\"} 
{\"abc\":\"def\", \"ghi\":\"jkl\"} 
2

在这种特殊情况下,regex应该寻找那些被继续进行{space一个字,或,和后面没有"

String str = "{abc:\"def\", ghi:\"jkl\"}"; 
String regex = "(?:[{ ,])(\\w+)(?!\")"; 
System.out.println(str.replaceAll(regex, "\\\"$1\\\"")); 

DEMOregex解释