简体   繁体   English

如何在Objective-C中正确地逃避这个正则表达式?

[英]How can I escape this regex properly in Objective-C?

I have the following regex I would like to escape in Objective-C 我有以下正则表达式,我想在Objective-C中逃避

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

Not exactly sure how to escape it so it works in Objective-C 不完全确定如何逃避它,因此它在Objective-C中工作

Update: 更新:

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];

Gives me an error about Parse Issue - Unexpected Identifier 给我一个关于Parse Issue - Unexpected Identifier的错误

Backslashes are used as escape characters in C strings. 反斜杠用作C字符串中的转义字符。 To make a regexp that contains backslashes as regex escapes, you need to double them. 要使包含反斜杠的正则表达式作为正则表达式转义,您需要将它们加倍。

Following on from the correct solution by millimoose, here is a NSString category method I use to escape black slashes for Regex patterns in Objective C. 通过millimoose从正确的解决方案继续,这是一个NSString类别方法,我用来逃避目标C中的正则表达式模式的黑色斜杠。

+ (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;
    }
}

Usage example: 用法示例:

NSString* pattern = [NSString escapeBackslashes:pattern];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM