0

我想知道如何获取以 &abc 开头并以 & 结尾的特定字符串。我尝试使用 had prefix 和 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 直到 "#"???? 可以帮助我

4

2 回答 2

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);
于 2013-04-11T15:45:28.040 回答
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);
}
于 2013-04-11T15:52:38.850 回答