如何获取字符串以& abc开头,以&结尾

时间:2013-04-11 15:28:10

标签: objective-c nsstring

我想知道如何获取以& abc开头并以&结尾的特定字符串。我试过有前缀和sufix。但这不是新行,

&安培; XYZ; 123:183:184:142安培;
&安培; ABC; 134:534:435:432安培;
&安培; QWE; 323:535:234:532&安培;

我的代码:

NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:@"&abc" intoString:nil]; //
NSString *substring = nil;
[scanner scanString:@"&abc" intoString:nil]; // Scan the # character
if([scanner scanUpToString:@"&" intoString:&substring]) {
   // If the space immediately followed the &, this will be skipped
   [substrings addObject:substring];
   NSLog(@"substring is :%@",substring);
}
// do something with substrings
[substrings release];

如何制作“scanner scanUpToString:@”& abc“并计算”:“== 3直到”#“????可以帮助我

2 个答案:

答案 0 :(得分:3)

    NSArray *arr = [NSArray arrayWithObjects:@"&xyz;123:183:184:142&",
                    @"&abc;134:534:435:432&",
                    @"&qwe;323:535:234:532&",
                    @"& I am not in it",
                    @"&abc I am out &" ,nil];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] %@ AND self ENDSWITH[cd] %@",@"&abc",@"&"];

    NSLog(@"Sorted Array %@",[arr filteredArrayUsingPredicate:predicate]);
    NSArray *sortedArray = [arr filteredArrayUsingPredicate:predicate];

    NSMutableArray *finalResult = [NSMutableArray arrayWithCapacity:0];
    for(NSString *string in sortedArray)
    {
        NSString *content = string;
        NSRange range1 = [content rangeOfString:@"&abc"];
        if(range1.length > 0)
            content = [content stringByReplacingCharactersInRange:range1 withString:@""];

        NSRange range2 = [content rangeOfString:@"&"];
        if(range2.length > 0)
            content = [content stringByReplacingCharactersInRange:range2 withString:@""];

        [finalResult addObject:content];
    }

    NSLog(@"%@",finalResult);

答案 1 :(得分:0)

尝试使用NSRegularExpression

- (BOOL)isValidString:(NSString *)string
{
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"^&abc.*&$" options:0 error:NULL];
    NSTextCheckingResult *result = [regularExpression firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
    return (result != nil);
}