过滤后的NSArray无法正常工作?在NSString中

时间:2011-12-11 03:08:43

标签: ios nsarray

当我尝试过滤一个字符串数组时,我得不到匹配的值有一个?在使用filteredArrayUsingPredicate时:你可以用一个句子代替一个句子的URL吗?而你仍然得到同样的东西。

以下是简化代码:

-(void)test {

    NSArray *theURLs = [NSArray arrayWithObjects:@"http://www.google.com", @"http://www.google.com?test=1", nil];

    NSString *currentURL = @"http://www.google.com?test=1";
    NSLog(@"currentURL %@", currentURL);
    NSPredicate *matchURLPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[cd] %@", [currentURL lowercaseString]];
    NSLog(@"match predicate %@", matchURLPredicate);
    NSArray *filteredArray = [theURLs filteredArrayUsingPredicate:matchURLPredicate];
    NSLog(@"filtered array %@", filteredArray);
    if ([filteredArray count]== 0) {

        NSLog(@"http://www.google.com?test=1 should have been found, but  was not");

    } else {

        NSLog(@"http://www.google.com?test=1 was found");

    }

}

如果我只查找@“http://www.google.com”,则过滤得很好。

以下是更正后的代码:

-(void)test {

    NSArray *theURLs = [NSArray arrayWithObjects:@"http://www.google.com", @"http://www.google.com?test=1", nil];

    NSString *currentURL = @"http://www.google.com\\?test=1";
    NSLog(@"currentURL %@", currentURL);
    NSPredicate *matchURLPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[cd] %@", [currentURL lowercaseString]];
    NSLog(@"match predicate %@", matchURLPredicate);
    NSArray *filteredArray = [theURLs filteredArrayUsingPredicate:matchURLPredicate];
    NSLog(@"filtered array %@", filteredArray);
    if ([filteredArray count]== 0) {

        NSLog(@"http://www.google.com?test=1 should have been found, but  was not");

    } else {

        NSLog(@"http://www.google.com?test=1 was found");

    }

}

1 个答案:

答案 0 :(得分:1)

?可能是一个特殊字符。逃避它:

@"http://www.google.com\\?test=1"