我正在開發iOS應用程序。我從web服務接收json並將其解析到不同的NSStrings中。問題是有時候這些字符串包含了未被解碼的特殊字符。從NSString中刪除編碼?
例如,我可以得到:Test One"Two
作爲NSString。
如何從NSString中刪除像這樣的特殊字符?
我正在開發iOS應用程序。我從web服務接收json並將其解析到不同的NSStrings中。問題是有時候這些字符串包含了未被解碼的特殊字符。從NSString中刪除編碼?
例如,我可以得到:Test One"Two
作爲NSString。
如何從NSString中刪除像這樣的特殊字符?
我寫了這個類,回來協助從NSString剝離HTML。
的NSString + StripHTML
的NSString + StripHTML.h
#import <Foundation/Foundation.h>
@interface NSString (StripHTML)
-(NSString *)stringByStrippingHTML;
@end
的NSString + StripHTML.m
#import "NSString+StripHTML.h"
@implementation NSString (StripHTML)
-(NSString *) stringByStrippingHTML {
NSRange r;
NSString *s = [self copy];
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
return s;
}
@end
希望這有助於。
這不是我正在尋找的。該字符串實際上不是HTML格式。只有隨機代碼在裏面。此外,我不想刪除它,只是正確地表示它 – Stephen 2013-04-04 03:25:19
我想你想只是一個簡單的正則表達式替換:
這是Neevik顯示,Use regular expression to find/replace substring in NSString
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&[^;]*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);
這應該刪除您的特殊字符。
從他的評論從另一個答案:「我不想刪除它,只是正確地代表它。」另外,你的正則表達式太餓了:@「Roger&Ebert認爲" The Shining!"很棒。」我可能會建議'@「&#?[a-z0-9] +;」'用於模式和用例不區分大小寫的搜索。這讓你更加接近,但仍然非常簡單。 – Rob 2013-04-04 05:10:11
那些HTML轉義? – borrrden 2013-04-04 03:02:51
[Objective-C:如何替換HTML實體?](http://stackoverflow.com/questions/2364797/objective-c-how-to-replace-html-entities)和/或[HTML字符解碼在Objective-C /可可觸摸](http://stackoverflow.com/questions/1105169/html-character-decoding-in-objective-c-cocoa-touch) – 2013-04-04 03:03:28
我認爲這個答案可能會解決你的問題http:// stackoverflow.com/a/2843454/778552 – 2013-04-04 03:09:01