如何在macOS上转义反斜杠? [英] How to unescape backslashes on macOS?

查看:1005
本文介绍了如何在macOS上转义反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Localized.strings文件可能包含转义的字符,例如\n\".

Localized.strings files may contain escaped chars like \n and \".

我如何有效地使它们转义?

How do I efficiently unescape them?

我知道我可以编写自己的函数来查找\并将其删除,然后继续搜索第二个下一个字符(这样我就不会将\\变成空),但这不会t处理特殊的转义方法,例如八进制字符编号(例如LF的\012)以及其他可能的形式.

I know I could write my own function that looks for a \ and removes it and then keeps searching at the second-next character (so that I don't turn \\ into nothing), but that won't handle special escape methods such as an octal character numbers (e.g. \012 for a LF) and possibly other forms.

我认为NSString将为此提供功能,但我找不到任何功能.

I'd think that NSString would offer a function for that but I can't find any.

实际上,这似乎是 NSString剥离常规\转义的重复项字符如何?,但是这个问题有很多不好的答案,而没有一个正确的答案.用户不再活跃,这意味着那里没有人会接受正确的答案.应该如何在SO上处理?

Actually, this appears to be a duplicate of NSString strip regular \ escape characters how?, but that question has a lot of bad answers and not a single correct answer. And the user is not active any more, meaning no one will ever accept a correct answer there. How shall that be handled on SO?

推荐答案

这是一个自写的ObjC版本,适用于大多数情况.它为NSString定义了unescaped方法.

Here's a self-written ObjC version that works for most cases. It defines an unescaped method for NSString.

#import <Cocoa/Cocoa.h>

@interface NSString (BackslashUnescaping)
- (NSString*) unescaped;
@end

@implementation NSString (BackslashUnescaping)

- (NSString*) unescaped
{
    NSString *text = self;
    NSInteger charIndex = 0;
    while (true) {
        NSInteger textLen = text.length;
        if (charIndex >= textLen) {
            break;
        }
        NSRange remainingRange = NSMakeRange (charIndex, textLen-charIndex);
        NSRange charRange = [text rangeOfString:@"\\"options:0 range:remainingRange];
        if (charRange.length == 0) {
            // no more backslashes -> done
            break;
        }
        charIndex = charRange.location + 1;
        if (charIndex >= textLen) {
            // reached end of string -> exit loop
            break;
        }
        // check char following the backslash
        unichar nextChar = [text characterAtIndex:charIndex];
        unichar replacementChar;
        NSInteger skipLen = 1;
        if (nextChar >= 'a' && nextChar <= 'z') {
            if (nextChar == 'n') {
                replacementChar = '\n'; // LF
            } else if (nextChar == 'r') {
                replacementChar = '\r'; // CR
            } else if (nextChar == 't') {
                replacementChar = '\t'; // TAB
            } else if (nextChar == 'x') {
                // A hex char code
                const NSInteger xtraLen = 2;
                if (charIndex+xtraLen >= textLen) break;
                // Note: Does not make sure that both chars are valid hex chars
                NSString *code = [text substringWithRange:NSMakeRange(charIndex+1, 2)];
                char ch = strtol(code.UTF8String, NULL, 16);
                replacementChar = ch;
                skipLen += xtraLen;
            } else if (nextChar == 'u') {
                // A unicode char code
                const NSInteger xtraLen = 4;
                if (charIndex+xtraLen >= textLen) break;
                // Note: Does not make sure that all four chars are valid hex chars
                NSString *code = [text substringWithRange:NSMakeRange(charIndex+1, 4)];
                unichar ch = strtol(code.UTF8String, NULL, 16);
                replacementChar = ch;
                skipLen += xtraLen;
            } else {
                // an unknown escape code - this should be fixed
                NSAssert(false, @"There's a case missing for escaping \\%c", nextChar);
            }
        } else if (nextChar >= '0' && nextChar <= '9') {
            unichar nextChar2 = 0;
            if (charIndex > textLen) {  // get the second octal char
                nextChar2 = [text characterAtIndex:charIndex+1];
            }
            if (nextChar == '0' && (nextChar2 < '0' || nextChar2 > '9')) {
                // A short NUL (\0) char
                replacementChar = 0;
            } else {
                // An octal char code
                const NSInteger xtraLen = 2;
                if (charIndex+xtraLen >= textLen) break;
                // Note: Does not make sure that the last char is a valid octal char
                NSString *code = [text substringWithRange:NSMakeRange(charIndex, 3)];
                char ch = strtol(code.UTF8String, NULL, 8); // https://stackoverflow.com/a/12820646/43615
                replacementChar = ch;
                skipLen += xtraLen;
            }
        } else {
            // Handle all generic escapes, like for \\ and \"
            replacementChar = nextChar;
        }
        #if 0 // Use string concatenation
            charIndex += skipLen-1;
            NSString *head = [text substringToIndex:charRange.location];
            NSString *tail = [text substringFromIndex:charIndex+1];
            text = [NSString stringWithFormat:@"%@%C%@", head, replacementChar, tail];
        #else // Use a mutable string
            if (text == self) {
                text = text.mutableCopy;
            }
            NSRange replacedRange = NSMakeRange(charRange.location, skipLen+1);
            NSString *replacement = [NSString stringWithCharacters:&replacementChar length:1];
            [(NSMutableString*)text replaceCharactersInRange:replacedRange withString:replacement];
            charIndex += 1;
        #endif 
    }
    return text;
}

@end 

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSArray *testValues = @[
            @"CR:\\rLF:\\n",
            @"\\\"quoted\\\"",
            @"Backslash: \\\\",
            @"Octal x (\170):\\170",
            @"Hex x (\x78):\\x78",
            @"Unicode Ф (\u0424):\\u0424",
            @"NUL char:\\0.",
            @"Bad Hex:\\x7x",   // this is not detected being invalid
            @"Bad Hex:\\x7",
            @"Incomplete :\\13"
        ];
        for (NSString *s in testValues) {
            NSString *s2 = [NSString stringWithFormat:@"Escaped:   %@\nUnescaped: %@", s, s.unescaped];
            printf("\n%s\n", s2.UTF8String);
        }
    }
    return 0;
}

这篇关于如何在macOS上转义反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆