NSString strip regular \ escape characters how?

荒凉一梦 提交于 2019-12-10 10:43:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!