gpt4 book ai didi

java - java中的循环定界符,消息损坏到数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:54 24 4
gpt4 key购买 nike

我有一个字符串:

String received = "28,gZrate:-1.48},
{gXrate:9.10,gYrate:-0.69,gZrate:-1.50},
{gXrate:9.22,gYrate:0.54,gZrate:-1.67},
{gXrate:9.20,gYrate:-2.40,gZrate:-1.65},{gXrate:9.02" ;

我需要这个字符串在这样的数组中:

["gXrate:9.10,gYrate:-0.69,gZrate:-1.50","gXrate:9.22,gYrate:0.54,gZrate:-1.67","gXrate:9.20,gYrate:-2.40,gZrate:-1.65"]

忽略接收字符串开头和结尾的破损部分即

28,gZrate:-1.48}

{gXrate:9.02 ;

还要注意有时字符串可能不会损坏。

最佳答案

String received = "28,gZrate:-1.48},{gXrate:9.10,gYrate:-0.69,gZrate:-1.50},";
received += "{gXrate:9.22,gYrate:0.54,gZrate:-1.67},";
received += "{gXrate:9.20,gYrate:-2.40,gZrate:-1.65},{gXrate:9.02";
String pattern = "\\{(.*?)\\},?";
StringBuilder sb = new StringBuilder("[");
boolean first = true;

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(received);
while (m.find()) {
if (!first) {
sb.append(",");
}
first = false;
sb.append("\"" + m.group(1) + "\"");
}
sb.append("]");
System.out.println(sb);

输出:

["gXrate:9.10,gYrate:-0.69,gZrate:-1.50","gXrate:9.22,gYrate:0.54,gZrate:-1.67","gXrate:9.20,gYrate:-2.40,gZrate:-1.65"]

这是一个演示,显示上述代码适用于损坏和平衡情况:

Rextester

关于java - java中的循环定界符,消息损坏到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43405083/

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