我有以下字符串,如何提取位于两个定界符之间的文本:

some text to be extracted

text text text text

= = = = = = = = = = = = =

some text to be extracted

= = = = = = = = = = = = =

text text text text


我也希望两个分隔符与文本一起返回。
如何用Objective-C完成?

最佳答案

这是一种方法。

您必须找到分隔符字符串所在的所有范围。

然后,将范围乘2乘2来提取它们之间的字符串:

    NSString *str = @"text text text text --- some text to be extracted... --- text text text text";

    NSString *myDelimiterString = @"---";

    NSMutableArray *arrayOfRangeForOccurrences = [[NSMutableArray alloc] init];
    NSUInteger length = [str length];
    NSRange range = NSMakeRange(0, length);
    while(range.location != NSNotFound)
    {
        range = [str rangeOfString:myDelimiterString options:0 range:range];
        if(range.location != NSNotFound)
        {
            [arrayOfRangeForOccurrences addObject:[NSValue valueWithRange:range]];
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
        }
    }

    //at least 2 delimiters have been found, we can extract a string
    if (arrayOfRangeForOccurrences.count >= 2) {
        //Extracting first text :
        NSRange firstRangeForDelimiter = [[arrayOfRangeForOccurrences objectAtIndex:0] rangeValue];
        NSRange secondRangeForDelimiter = [[arrayOfRangeForOccurrences objectAtIndex:1]rangeValue];

        NSRange rSub = NSMakeRange(firstRangeForDelimiter.location + firstRangeForDelimiter.length, secondRangeForDelimiter.location - firstRangeForDelimiter.location - firstRangeForDelimiter.length);
        NSString *myExtractedText = [str substringWithRange:rSub];
        NSLog(@"myExtractedText is : %@", myExtractedText);
    } else {
        NSLog(@"No pair of delimiter found");
    }

10-01 15:57
查看更多