问题
I need an efficient piece of code that strips escape characters. This is regular escapes not HTML escape characters.
Example: "\"", "\\\\", "\", "\\"
I want a general algorithm to strip any kind of escape sequences.
Could use any utility like regular expression.
(NSString*) unescape:(NSString*) string {
....
}
This is the answer I wrote:
-(NSString*) unescape:(NSString*) string
{
for(int i = 0; i < string.length; i++) {
char a = [string characterAtIndex:i];
if([string characterAtIndex:i] == '\\' ) {
string = [string stringByReplacingCharactersInRange:NSMakeRange(i,1) withString:@""];
}
}
return string;
}
回答1:
Try to use below code for HTML escape
(NSString*) unescape:(NSString*) string
{
return [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
for regular Escape
(NSString*) unescape:(NSString*) string
{
return [string stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
}
回答2:
The best method that you should use is:
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
You would call it using:
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
回答3:
If you want to use regex, you can try with regex pattern \\[bntr\\\\"]
. Or use any required regex pattern here.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
@"\\[bntr\\\\"]" options:0 error:nil];
[regex replaceMatchesInString:str options:0 range:NSMakeRange(0, [str length]) withTemplate:@""];
回答4:
I apoligize for my answer...
NSString *_string = @"\\\\ dfsdg \\ tr\\\\t \\\\\\tw\\\\\\\\w\\ t\\ \\\\ \\ \\\\\\ rret\\ \\\\ \\\\\\\\";
NSLog(@"%@", [_string stringByReplacingOccurrencesOfString:@"\\" withString:@""]);
result is:
dfsdg trt tww t rret
回答5:
If its URL Encoded, you are probably looking for:
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding
回答6:
Hope this helps:
-(NSString *)unescape:(NSString *)string
{
if ([string rangeOfString:@"\\"].location != NSNotFound)
{
[string stringByReplacingCharactersInRange:@"\\" withString:@"\\"];
}
else if ([string rangeOfString:@"\\\\"].location != NSNotFound)
{
[string stringByReplacingCharactersInRange:@"\\\\" withString:@"\\"];
}
else if ([string rangeOfString:@"\\\\"].location != NSNotFound)
{
[string stringByReplacingCharactersInRange:@"\\\\" withString:@"\\"];
}
}
来源:https://stackoverflow.com/questions/13424402/nsstring-strip-regular-escape-characters-how