NSString在String中间获取字符串

时间:2015-07-07 05:41:24

标签: ios objective-c nsstring

我有一堆字符串,我想总是在{和}之间获取字符串,包括括号。所以,如果我有

len(revenue)

我想要输出

@"alsdkfj {'asdf':'stuff stuff'} more stuff"

我怎么能这样做?字符串总是不同所以我不能只搜索“alsdkfj”,我需要不知道它是什么才能进入{}

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码获取多个subString。

  NSString* placeHolderString = @"alsdkfj {'asdf':'stuff stuff'} more stuff";
    NSRegularExpression* faceRegexQuota = [[NSRegularExpression alloc] initWithPattern:@"\\{(.*?)\\}" options:0 error:NULL];
    [faceRegexQuota enumerateMatchesInString:placeHolderString options:0 range:NSMakeRange(0, [placeHolderString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

        NSString* matchText = [placeHolderString substringWithRange:[match range]];
        NSLog(@"Output : %@",matchText);

    }];

输出:{' asdf':'东西'}

答案 1 :(得分:1)

使用以下代码。

NSString *finalString = @"alsdkfj {'asdf':'stuff stuff'} more stuff";
NSRange range2 = [content rangeOfString:@"{"];
NSRange range3 = [content rangeOfString:@"}"];
int lengt = range3.location - range2.location - range2.length;
int location = range2.location + range2.length;
NSRange range4;
range4.location = location;
range4.length = lengt;
finalString = [finalString substringWithRange:range4];
finalString = [NSString stringWithFormat:@"{%@}",finalString];