使用NSRegularExpression命名捕获组

Dov*_*Dov 8 regex cocoa objective-c nsregularexpression

是否NSRegularExpression支持命名捕获组?它从文档中看起来不像,但我想在探索替代解决方案之前进行检查.

Nev*_*ess 10

iOS中不支持命名分组,我所能做的就是利用Enum:

枚举:

typedef enum
{
    kDayGroup = 1,
    kMonthGroup,
    kYearGroup
} RegexDateGroupsSequence;
Run Code Online (Sandbox Code Playgroud)

示例代码:

NSString *string = @"07-12-2014";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{2})\\-(\\d{2})\\-(\\d{4}|\\d{2})"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
    NSString *day = [string substringWithRange:[match rangeAtIndex:kDayGroup]];
    NSString *month = [string substringWithRange:[match rangeAtIndex:kMonthGroup]];
    NSString *year = [string substringWithRange:[match rangeAtIndex:kYearGroup]];


    NSLog(@"Day: %@, Month: %@, Year: %@", day, month, year);
}
Run Code Online (Sandbox Code Playgroud)


Ort*_*ntz 5

iOS 11使用-[NSTextCheckingResult rangeWithName:]API 引入了命名捕获支持。

要获取具有名称和名称及其关联值的字典,您可以使用此扩展(用Swift编写,但可以从Objective C调用):

@objc extension NSString {
    public func dictionaryByMatching(regex regexString: String) -> [String: String]? {
        let string = self as String
        guard let nameRegex = try? NSRegularExpression(pattern: "\\(\\?\\<(\\w+)\\>", options: []) else {return nil}
        let nameMatches = nameRegex.matches(in: regexString, options: [], range: NSMakeRange(0, regexString.count))
        let names = nameMatches.map { (textCheckingResult) -> String in
            return (regexString as NSString).substring(with: textCheckingResult.range(at: 1))
        }
        guard let regex = try? NSRegularExpression(pattern: regexString, options: []) else {return nil}
        let result = regex.firstMatch(in: string, options: [], range: NSMakeRange(0, string.count))
        var dict = [String: String]()
        for name in names {
            if let range = result?.range(withName: name),
                range.location != NSNotFound
            {
                dict[name] = self.substring(with: range)
            }
        }
        return dict.count > 0 ? dict : nil
    }
}
Run Code Online (Sandbox Code Playgroud)

来自Objective-C的电话:

(lldb) po [@"San Francisco, CA" dictionaryByMatchingRegex:@"^(?<city>.+), (?<state>[A-Z]{2})$"];
{
    city = "San Francisco";
    state = CA;
}
Run Code Online (Sandbox Code Playgroud)

代码说明:该函数首先需要找出命名捕获的列表。不幸的是,Apple没有为此发布API(rdar:// 36612942)。