简体   繁体   中英

ObjC Format Regex for Value of (Grails style) Key-Value Pair

So assuming a properties file like so (application.properties in Grails, for example):

app.name=An App Name
other.keys=Other Values
more.keys=More Values

I'm trying to write an Objective-C style regex to extract the value An App Name .

So far, using some sample code to test this out, heres what I've got:

    NSError *errRegex = NULL;
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:@"^app.name=(.*?)$"
                                  options:NSRegularExpressionCaseInsensitive
                                  error:&errRegex];


    NSUInteger countMatches = [regex numberOfMatchesInString:strSource options:0 range:NSMakeRange(0, [strSource length])];
    NSLog(@"Number of Matches: %ld", countMatches);

    NSLog(@"-----");

    [regex enumerateMatchesInString:strSource options:0
                              range:NSMakeRange(0, [strSource length])
                         usingBlock:^(NSTextCheckingResult *match,
                                      NSMatchingFlags flags, BOOL *stop) {

                             NSLog(@"Ranges: %ld", [match numberOfRanges]);

                             NSString *matchFull = [strSource substringWithRange:[match range]];
                             NSLog(@"Match: %@", matchFull);

                             for (int i = 0; i < [match numberOfRanges]; i++) {
                                 NSLog(@"\tRange %i: %@", i,
                                       [strSource substringWithRange:[match rangeAtIndex:i]]);
                             }                              
                         }];

    if (errRegex) {
        NSLog(@"%@", errRegex);
    }

And I'm getting the following output:

2013-12-11 11:34:54.408 test[7321:303] Number of Matches: 1
2013-12-11 11:34:54.409 test[7321:303] -----
2013-12-11 11:34:54.409 test[7321:303] Ranges: 2
2013-12-11 11:34:54.410 test[7321:303] Match: app.name=An App Name        other.keys=Other     Values        more.keys=More Values
2013-12-11 11:34:54.410 test[7321:303]  Range 0: app.name=An App Name        other.keys=Other Values        more.keys=More Values
2013-12-11 11:34:54.410 test[7321:303]  Range 1: An App Name        other.keys=Other Values        more.keys=More Values

I'm assuming I need to end the regex at a newline character, but anything I've tried returns 0 matches.

试试这个模式:

^app\.name=(.*)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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