1

我有一个像这样的字符串:


?key=123%252Bf-34Fa&name=John
?name=Johon&key=123%252Bf-34Fa

我想获得的值key,我使用这个 NSRegularExpression (?i)(?<=key=)[.?!&]+[?=&]?? 我认为该模式就像匹配除“&”之外的任何字符。但结果总是NULL

每个键的值可以是除“&”之外的任何值。那么如何创建正确的 NSRegularExpression?谢谢。

4

2 回答 2

8

你不应该为此使用正则表达式,特别是如果你不知道如何。相比:

NSString *string = @"?name=Johon&key=123%252Bf-34Fa";
// NSString *string = @"?key=123%252Bf-34Fa&name=John";

// one way
NSRange range = [string rangeOfString:@"key="];
if (range.location!=NSNotFound){
    string = [string substringFromIndex:NSMaxRange(range)];
    range = [string rangeOfString:@"&"];
    if (range.location!=NSNotFound){
        string = [string substringToIndex:range.location];
    }
}

// another way
__block NSString *keyValue = nil;
[[string componentsSeparatedByString:@"&"] enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop){
    NSRange range = [object rangeOfString:@"key="];
    if (range.location!=NSNotFound){
        keyValue = [object substringFromIndex:range.location+range.length];
        *stop = YES;
    }
}];

// regex way
NSString *regexStr = @"[\\?&]key=([^&#]*)";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
// enumerate all matches
if ((regex==nil) && (error!=nil)){
    NSLog( @"Regex failed for url: %@, error was: %@", string, error);
} else {
    [regex enumerateMatchesInString:string 
                            options:0 
                              range:NSMakeRange(0, [string length]) 
                         usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
                             if (result!=nil){
                                 // iterate ranges
                                 for (int i=0; i<[result numberOfRanges]; i++) {
                                     NSRange range = [result rangeAtIndex:i];
                                     NSLog(@"%ld,%ld group #%d %@", range.location, range.length, i, 
                                           (range.length==0 ? @"--" : [string substringWithRange:range]));
                                 }
                             }
                         }];
}
于 2011-09-16T10:29:50.537 回答
0

我知道答案发布已经有好几年了,但是虽然 Jano 答案中的代码在技术上是正确的,但rangeOfString多次调用效率非常低。

正则表达式实际上非常简单。您可以执行以下两项操作之一:

key=([^&\s]+) // searches for the key
              // matches all characters other than whitespace characters
              //   and ampersands
([^&?\s]+)=([^&\s]+)  // searches for key/value pairs
                      // key matches all characters other than whitespace characters
                      //   and ampersands and question marks
                      // value matches all characters other than whitespace characters
                      //   and ampersands

Objective-C using 中的代码NSRegularExpression如下所示:

NSString *stringToSearch = @"?name=John&key=123%252Bf-34Fa"

NSError *error;
NSRegularExpression *findKey = [NSRegularExpression regularExpressionWithPattern:@"key=([^&\\s]+)" options:0 error:&error];
if (error) {
    // log error
}

NSString *keyValue;
NSTextCheckingResult *match = [findKey firstMatchInString:stringToSearch options:0 range:NSMakeRange(0, stringToSearch.length)];
if (match) {
    NSRange keyRange = [match rangeAtIndex:1];
    keyValue = [stringToSearch substring:keyRange];
}

或像这样:

NSString *stringToSearch = @"?name=John&key=123%252Bf-34Fa"

NSError *error;
NSRegularExpression *findParameters = [NSRegularExpression regularExpressionWithPattern:@"([^&?\\s]+)=([^&\\s]+)" options:0 error:&error];
if (error) {
    // log error
}

NSMutableDictionary *keyValuePairs = [[NSMutableDictionary alloc] init];
NSArray *matches = [findParameters matchesInString:stringToSearch options:0 range:NSMakeRange(0, stringToSearch.length)];
for (NSTextCheckingResult *match in matches) {
    NSRange keyNameRange = [match rangeAtIndex:1];
    NSRange keyValueRange = [match rangeAtIndex:2];
    keyValuePairs[[stringToSearch substring:keyNameRange]] = [stringToSearch substring:keyValueRange];
}

在实际代码中使用正则表达式时,请注意双反斜杠 (\\) 以转义反斜杠。

于 2014-08-27T17:08:21.887 回答