我为同样的问题推荐,但我没有得到答案,我试着2天没有得到它,任何人都可以帮助我。
我需要查找并打印以“&”开头和结尾的字符串。但在我的字符串中出现了大量相同的“&”
EX:
&安培; 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);
答案 0 :(得分: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&