2017-03-03 30 views
0

我有以下字符串,我試圖執行正則表達式字符串提取:{"code":5,"id":104,"message":"Not working"}。我需要執行提取,因爲有時多個字符串可能會捆綁在一起,如下所示:{.....}{...}{......}NSRegularExpression捕獲部分無效的JSON

我已經使用JSONSerialization作爲個別消息進來的情況:{"code":5,"id":104,"message":"Not working"}

我需要正則表達式來提取單個字符串,當我得到這樣的消息:{"code":5,"id":104,"message":"Not working"}{"code":5,"id":101,"message":"some message"}{"code":5,"id":105,"message":"test"}

我有一個字符串相匹配的正則表達式如下:{.*?"id":104.*?}

NSError *error = NULL; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"{.*?\"id\":104.*?}" options:NSRegularExpressionCaseInsensitive error:&error]; 
//regex is returning (null) here 

NSRange range = [regex rangeOfFirstMatchInString:msg options:0 range:NSMakeRange(0, [msg length])]; 

NSString *result = [msg substringWithRange:range]; 
//Result is empty 

[regex enumerateMatchesInString:msg options:0 range:NSMakeRange(0, [msg length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { 
    NSRange range = [result rangeAtIndex:1]; 
    NSString *regexStr = [msg substringWithRange:range]; 
}]; 

我相信這個問題是我的正則表達式。我可能不會正確地轉義它。

我試過{.*?\\\"id\\\":104.*?}但結果是一樣的。

我是否正確地說我需要一個正則表達式來管理和提取字符串,當多個到達?

+0

我認爲它是一種JOSN甲的你爲什麼不使用JSONSerilation此? – CodeChanger

+0

是這個'{「code」:5,「id」:104,「message」:「Not working」}'string or dictioanry –

+0

如上所述 - 看起來您正在使用錯誤的工具進行工作。對我來說,這看起來像JSON。其中正則表達式不是正確的做法 – Tander

回答

1
NSString *string = @"{\"code\":5,\"id\":104,\"message\":\"Not working\"}{\"code\":5,\"id\":101,\"message\":\"some message\"}{\"code\":5,\"id\":105,\"message\":\"test\"}"; 

    NSLog(@"String: %@", string); 

    NSMutableArray *allSubDictAsStr = [[NSMutableArray alloc] init]; 

    NSString *pattern = @"\\{.*?\\}"; 
    NSError *errorRegex = nil; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&errorRegex]; 
    NSArray *results = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])]; 
    for (NSTextCheckingResult *aResult in results) 
    { 
    NSString *subJSONStr = [string substringWithRange:[aResult range]]; 
    [allSubDictAsStr addObject:subJSONStr]; 
    } 
    NSString *bigJSONStr = [NSString stringWithFormat:@"[%@]", [allSubDictAsStr componentsJoinedByString:@","]]; 

    NSError *errorJSON = nil; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:[bigJSONStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&errorJSON]; 
    NSLog(@"JsonArray: %@", jsonArray); 

這是一個可行的解決方案,它不是真的乾淨,但我得到了與正則表達式玩。你的問題可能更多的是你的WebSocket分析。

建議:
•使用正則表達式隔離每個Dictionary JSON。
•然後構造一個「字典JSON數組」(bigJSONStr,在我們的例子中爲NSString)。

對於該模式,請注意,您必須轉義{},因爲它們是以正則表達式保留的。 我沒有檢查NSError參數,這當然不推薦。

編輯:
附加說明/修改:與其構建「bigJSONStr」(這是相當醜陋的)

NSMutableArray *allResponses = [[NSMutableArray alloc] init]; 
... 
for (NSTextCheckingResult *aResult in results) 
{ 
    NSString *subJSONStr = [string substringWithRange:[aResult range]]; 
    NSError *errorJSON = nil; 
    NSDictionary *aResponseDict = [NSJSONSerialization JSONObjectWithData:[subJSONStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&errorJSON]; 
    if (!errorJSON) [allResponses addObject:subJSONStr]; 
} 
NSLog(@"allResponses: %@", allResponses); 
+0

我需要做的就是逃避'{'和'}'。非常感謝Larme – mhorgan

0

不喜歡

//{"code":5,"id":104,"message":"Not working"} 

// initially convert your JSON string to NSData 
NSData *objectData = [JsonString dataUsingEncoding:NSUTF8StringEncoding]; 
    NSError *error; 
// deserialize using NSJSONSerialization 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error]; 

// then serilize what ever your string 
if (json) 
{ 
NSString * code = json[@"code"]; 
NSString * ide = json[@"id"]; 
NSString * message = json[@"message"]; 
} 
+1

不要發佈僅限代碼的答案。提供一些信息,你已經做了什麼,爲什麼是這樣。 – 2017-03-03 12:38:14

+1

@Sneak - 說明更新 –

+0

Upvoted。請保持它在您的其他職位類似。好工作。 – 2017-03-03 12:39:20