gpt4 book ai didi

java - 如何使用嵌套组在java中用正则表达式替换字符串

转载 作者:行者123 更新时间:2023-11-30 07:18:29 35 4
gpt4 key购买 nike

我有格式行

"123","45","{"VFO":[B501], "AGN":[605,B501], "AXP":[665], "QAV":[720,223R,251Q,496M,548A,799M]}","4"

它可以更长,但它总是包含

"number","number","someValues","digit"

我需要用引号将值包装在 someValues 内

对于测试字符串,预期结果应该是。

"123","45","{"VFO":["B501"], "AGN":["605","B501"], "AXP":["665"], "QAV":["720","223R","251Q","496M","548A","799M"]}","4"

请建议最简单的java解决方案。

附注

我的变体:

                        String valuePattern = "\\[(.*?)\\]";
Pattern valueR = Pattern.compile(valuePattern);
Matcher valueM = valueR.matcher(line);
List<String> list = new ArrayList<String>();
while (valueM.find()) {
list.add(valueM.group(0));
}
String value = "";
for (String element : list) {
element = element.substring(1, element.length() - 1);
String[] strings = element.split(",");
String singleGroup = "[";
for (String el : strings) {
singleGroup += "\"" + el + "\",";
}
singleGroup = singleGroup.substring(0, singleGroup.length() - 1);
singleGroup = singleGroup + "]";
value += singleGroup;
}
System.out.println(value);

最佳答案

已编辑

好的,这是我发现的最短的方法,在我看来它工作得很好,除了我必须手动添加的逗号和括号...有人可能可以立即做到这一点,但我找到了它处理嵌套组的替换很棘手。

import java.util.*;
import java.lang.*;
import java.io.*;

Pattern p = Pattern.compile("(\\[(\\w+))|(,(\\w+))");
Matcher m = p.matcher("\"123\",\"45\",\"{\"VFO\":[B501], \"AGN\":[605,B501], \"AXP\":[665], \"QAV\":[720,223R,251Q,496M,548A,799M]}\",\"4\"");
StringBuffer s = new StringBuffer();
while (m.find()){
if(m.group(2)!=null){
m.appendReplacement(s, "[\""+m.group(2)+"\"");
}else if(m.group(4)!=null){
m.appendReplacement(s, ",\""+m.group(4)+"\"");
}
}
m.appendTail(s);
print(s);

关于java - 如何使用嵌套组在java中用正则表达式替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37994212/

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