2015-12-17 69 views
1

我有這樣一個NSStringobjective c正則表達式3

<br /><b>Notice</b>: Undefined variable: success in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1225</b><br /><br /> 

<b>Warning</b>: pack(): Type H: illegal hex digit (in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /> 

<b>Warning</b>: pack(): Type H: illegal hex digit n in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /> 

<b>Warning</b>: pack(): Type H: illegal hex digit u in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /> 

<b>Warning</b>: pack(): Type H: illegal hex digit l in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /> 

<b>Warning</b>: pack(): Type H: illegal hex digit l in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /> 

<b>Warning</b>: pack(): Type H: illegal hex digit) in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /> 

<b>Notice</b>: Undefined variable: success in <b>/var/www/webservice/gcm/setMessage.php</b> on line 
    <b>1225</b><br />{"success":1,"success_message":"Edit listing success"} 

如何提取此{"success":1,"success_message":"Edit listing success"}部分。

+3

不是來自某個Web服務的完整JSON響應的字符串嗎? – NSNoob

+1

剪切帶起始字符「{」和結束字符「}」的字符串。答對了 !!!你會得到你想要的字符串,但只有當你的迴應以上面提到的格式出現時,這纔會起作用。也請檢查以上評論。 – nikhil84

+1

我可能虛心地建議修復服務器上的錯誤,然後將響應解析爲純JSON,這是一種更智能,更好,更簡單以及許多其他詞語的修復方法嗎? :) – TwoStraws

回答

2

只要這是您的字符串的一般格式,模式(\\{[^}]+\\})應該這樣做。下面是一些示例代碼,您開始:

NSString *test = @"<br /><b>Notice</b>: Undefined variable: success in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1225</b><br /><br /><b>Warning</b>: pack(): Type H: illegal hex digit (in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /><b>Warning</b>: pack(): Type H: illegal hex digit n in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /><b>Warning</b>: pack(): Type H: illegal hex digit u in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /><b>Warning</b>: pack(): Type H: illegal hex digit l in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /><b>Warning</b>: pack(): Type H: illegal hex digit l in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /><b>Warning</b>: pack(): Type H: illegal hex digit) in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1434</b><br /><br /><b>Notice</b>: Undefined variable: success in <b>/var/www/webservice/gcm/setMessage.php</b> on line <b>1225</b><br />{\"success\":1,\"success_message\":\"Edit listing success\"}"; 

NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(\\{[^}]+\\})" options:0 error:nil]; 
NSTextCheckingResult *result = [regex firstMatchInString:test options:0 range:NSMakeRange(0, test.length)]; 
NSString *match = [test substringWithRange:result.range]; 

NSLog(@"Matched %@", match); 

你顯然應該處理錯誤更優雅不僅僅是忽略它們。