0

我申请了同样的问题,但我没有得到答案,我尝试了 2 天我没有得到它,任何人都可以帮助我。

我只需要查找并打印以“&”开头和结尾的字符串。但在我的字符串中很多相同的“&”出现

前任:

&abc;123:342:431:234& &xyz;232:2344:433:434& &pqr;234:453:534:3445&

我只想打印以“&xyz”开头然后以“&”结尾的字符串 (&xyz;232:2344:433:434&)

有时我会得到
&pqr;234:453:534:3445& &abc;123:342:431:234& &xyz;232:2344:433:434&

这里我也想打印相同的“&xyz”并以“&”结尾。

我试过了,“NSRange”,“NSscanner”,“NSpredictive”。但我不知道特定的字符串是 ptrit

// NSScanner :

    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];


// NSpredictive :

NSString *new=@"&abc;123:342:431:234& &xyz;232:2344:433:434& &pqr;234:453:534:3445&";

NSArray *arr = [new ComponentsSepetratedByString @:" "];

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);
4

1 回答 1

0

这是你想要的?

NSString *string = @"&abc;123:342:431:234& &xyz;232:2344:433:434& &pqr;234:453:534:3445&";

NSString *pattern = @"&xyz[^&]+&";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                       options:0 error:NULL];

[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length])
             usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                 NSRange range = [result range];
                 NSString *matched = [string substringWithRange:range];

                 NSLog(@"%@", matched);
             }];

输出:

&xyz;232:2344:433:434&
于 2013-04-15T07:36:08.063 回答