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

そして、私が望む結果は2つの部分文字列です。

{"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 に答える