我该如何在Objective-C中正确地转义这个正则表达式?

4

我有以下正则表达式需要在Objective-C中转义

/\B\$((?:[0-9]+(?=[a-z])|(?![0-9\.\:\_\-]))(?:[a-z0-9]|[\_\.\-\:](?![\.\_\.\-\:]))*[a-z0-9]+)/ig;

我不太确定如何转义它,以便在Objective-C中使用

更新:

NSString* pattern = @"/\\B\\$((?:[0-9]+(?=[a-z])|(?![0-9\\.\\:\\_\\-]))(?:[a-z0-9]|[\\_\\.\\-\\:](?![\\.\\_\\.\\-\\:]))*[a-z0-9]+)/ig;";
NSRegularExpression *usernameRegex = [[[NSRegularExpression alloc] initWithPattern:pattern
                                                                  options:NSRegularExpressionCaseInsensitive 
                                                                    error:nil];
                                                                        error:nil];

给我一个错误,提示“解析问题-意外标识符”。
2个回答

7

在C字符串中,反斜杠被用作转义字符。如果要创建一个包含反斜杠的正则表达式,需要将其加倍。


0
继millimoose提出的正确解决方案之后,下面是我在Objective C中使用的一个NSString类别方法,用于转义正则表达式模式中的反斜杠。
+ (NSString *)escapeBackslashes:(NSString *)regexString
{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\\\" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators | NSRegularExpressionAnchorsMatchLines | NSRegularExpressionAllowCommentsAndWhitespace error:&error];
    if (error == NULL)
    {
        return [regex stringByReplacingMatchesInString:regexString options:0 range:NSMakeRange(0, [regexString length]) withTemplate:@"\\\\"];
    }
    else
    {
        return regexString;
    }
}

使用示例:

NSString* pattern = [NSString escapeBackslashes:pattern];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接