我在检测到3个新线路实例后尝试修剪NSString。 (\ n)的。所以,这就是我尝试过的:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [myString length])];
现在,匹配的数量总是超过3,我想在它击中第三个\ n时停止字符串。有没有人知道这样做有什么好的逻辑?
答案 0 :(得分:1)
如果3个新的行实例总是组合在一起,那很容易:
NSString *testString = @"The quick brown fox jumps \n\n\n over the lazy dog. \n\n\n New Line.";
[[string componentsSeparatedByString:@"\n\n\n"] firstObject]
否则你可以使用:
NSError *error;
NSString *pattern = @"(\\A|\\n\\s*\\n\\s*\\n)(.*?\\S[\\s\\S]*?\\S)(?=(\\Z|\\s*\\n\\s*\\n\\s*\\n))";
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex enumerateMatchesInString:testString
options:0
range:NSMakeRange(0, [testString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSString *match = [testString substringWithRange:[result rangeAtIndex:2]];
NSLog(@"match = '%@'", match);
}];
(取自this回答)
答案 1 :(得分:0)
NSString* originalString = @"This\nis\na\ntest string";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@".*\\n.*\\n.*\\n" options:0 error:nil];
NSRange range = [regex rangeOfFirstMatchInString:originalString options:0 range:(NSRange){0,originalString.length}];
NSString* trimmedString = [originalString substringFromIndex:range.length];
NSLog(@"Original: %@", originalString);
NSLog(@"Trimmed: %@", trimmedString);
打印:
2015-02-05 21:39:41.491 TestProject[4258:1269568] Original: This
is
a
test string
2015-02-05 21:39:41.492 TestProject[4258:1269568] Trimmed: test string