gpt4 book ai didi

java - 带引号的字符串输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:13 25 4
gpt4 key购买 nike

我输入字符串如下

{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED}

我想在我的输出中将上面的字符串转换为如下所示...,想为字符串添加引号(键,值对)。

{"key": "IsReprint", "value":"COPY"};{"key": "IsCancelled", "value":"CANCELLED"}

请协助..提前致谢..

    String input="{key: IsReprint, value:COPY};{key: IsCancelled,value:CANCELLED}";
if(input.contains("key:") && input.contains("value:") ){
input=input.replaceAll("key", "\"key\"");
input=input.replaceAll("value", "\"value\"");
input=input.replaceAll(":", ":\"");
input=input.replaceAll("}", "\"}");
input=input.replaceAll(",", "\",");
//System.out.println("OUTPUT----> "+input);
}

如果输入字符串如下,我上面的代码有问题

{key: BDTV, value:Africa Ltd |注册号:433323240833-C23441,GffBLAB |增值税号:4746660239035
6级

最佳答案

您可以使用正则表达式来完成相同的操作,但更简洁:

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

public class JsonScanner {

private final static String JSON_REGEX = "\\{key: (.*?), value:(.*?)(\\};|\\}$)";

/**
* Splits the JSON string into key/value tokens.
*
* @param json the JSON string to format
* @return the formatted JSON string
*/
private String findMatched(String json) {
Pattern p = Pattern.compile(JSON_REGEX);
Matcher m = p.matcher(json);
StringBuilder result = new StringBuilder();

while (m.find()) {
result.append("\"key\"=\"" + m.group(1) + "\", ");
result.append("\"value\"=\"" + m.group(2) + "\" ; ");
System.out.println("m.group(1)=" + m.group(1) + " ");
System.out.println("m.group(2)=" + m.group(2) + " ");
System.out.println("m.group(3)=" + m.group(3) + "\n");
}

return result.toString();
}

public static void main(String... args) {
JsonScanner jsonScanner = new JsonScanner();
String result = jsonScanner.findMatched("{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}<br/>Plot No.56634773,Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}<br />Plot No. 56634773, Road}");
System.out.println(result);
}

}

您可能需要调整正则表达式或输出字符串以满足您的确切要求,但这应该让您了解如何开始......

关于java - 带引号的字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44240318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com