NSString - 如何使用花括号包围String的一部分

时间:2014-08-21 10:26:52

标签: ios iphone nsstring

我的回复将采用以下格式:{group} community announced: {announcement}

根据{}内的文字,我必须查询字典。我尝试使用

componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{}"]

但它返回了很多细节:

(
    "",
    group,
    " community announced: ",
    announcement,
    ""
)

那么如何在数组中准确获取{}内的字符。

3 个答案:

答案 0 :(得分:4)

使用NSRegularExpression

NSString *string = @"{group} community announced: {announcement}";

NSMutableArray *array = [[NSMutableArray alloc] init];

NSString *pattern = @"\\{((.|\n)*?)\\}";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
if (!error)
{
    NSArray *allMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    for (NSTextCheckingResult *aMatch in allMatches)
    {
        NSRange matchRange = [aMatch range];
        NSString *foundString = [string substringWithRange:NSMakeRange(matchRange.location+1, matchRange.length-2)];
        [array addObject:foundString];
    }
}
NSLog(@"Array: %@", array);

输出:

  

数组:(       组,       公告)

答案 1 :(得分:0)

让我们试试这个嵌套的方法调用

NSString *myString = @"{group} community announced: {announcement}";

[self logTheSplittedString:myString];

- (void)logTheSplittedString:(NSString *)targetString
{
    NSRange start = [targetString rangeOfString:@"{"];
    NSRange end = [targetString rangeOfString:@"}"];

    NSString *betweenBraces1 = @"";

    if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location)
    {
        betweenBraces1 = [targetString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
        NSLog(@"%@",betweenBraces1);
    }

    targetString = [targetString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"{%@}",betweenBraces1] withString:@""];

    NSRange startNext = [targetString rangeOfString:@"{"];
    NSRange endNext = [targetString rangeOfString:@"}"];

    if (startNext.length != 0 && endNext.length != 0)
    {
        [self logTheSplittedString:targetString];
    }
}

<强>输出

  


  通告

答案 2 :(得分:0)

您可以使用正则表达式在&#39; {text}&#39;之间找到字符串。 请参阅以下代码

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"{(.*)}" options:NSRegularExpressionCaseInsensitive error:&error];
    [regex enumerateMatchesInString:responceString options:0 range:NSMakeRange(0, [responceString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        // detect
        NSString *strFind1 = [responceString substringWithRange:[match rangeAtIndex:1]];
        //log
        NSLog(@"%@",strFind1);
    }];