gpt4 book ai didi

java - 在字符串中查找 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 03:55:11 25 4
gpt4 key购买 nike

继我关于 me having to deal with a poorly implemented chat server 的问题之后,我得出的结论是我应该尝试从其他服务器响应中获取聊天消息。

基本上,我收到一个如下所示的字符串:

13{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat {message 1\"}","sender":123,"recipient":321}45{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat} message 2\"}","sender":123,"recipient":321}1

我想要的结果是两个子字符串:

{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat {message 1\"}","sender":123,"recipient":321}
{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat} message 2\"}","sender":123,"recipient":321}

我可以接收到的输出是 JSON 对象(可能包含其他 JSON 对象)和一些数字数据的混合。

我需要从该字符串中提取 JSON 对象。

我考虑过计算大括号来选择第一个开始大括号和相应的结束大括号之间的内容。但是,消息可能包含花括号。

我考虑过正则表达式,但我找不到一个可行的(我不擅长正则表达式)

关于如何进行的任何想法?

最佳答案

这应该有效:

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile(
"\\{ # Match an opening brace. \n" +
"(?: # Match either... \n" +
" \" # a quoted string, \n" +
" (?: # which may contain either... \n" +
" \\\\. # escaped characters \n" +
" | # or \n" +
" [^\"\\\\] # any other characters except quotes and backslashes \n" +
" )* # any number of times, \n" +
" \" # and ends with a quote. \n" +
"| # Or match... \n" +
" [^\"{}]* # any number of characters besides quotes and braces. \n" +
")* # Repeat as needed. \n" +
"\\} # Then match a closing brace.",
Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}

关于java - 在字符串中查找 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13469190/

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