1

在我的问题是我不得不处理一个实施不善的聊天服务器之后,我得出的结论是我应该尝试从其他服务器响应中获取聊天消息。

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

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 对象。

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

我已经考虑过正则表达式,但我找不到一个可以工作的(我不擅长正则表达式)

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

4

1 回答 1

1

这应该有效:

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());
} 
于 2012-11-20T08:40:04.883 回答