我有一个像
这样的字符串 NSString * aString = @"\n \n \n This is my string ";
我需要将第一个空格和新行字符提取到第一个非空格非换行符。那就是输出应该是
NSString *output = @"\n \n \n ";
我用NSScanner
尝试了如下
NSString * aString = @" \ n \ n \ n这是我的字符串&#34 ;;
NSScanner *scanner = [NSScanner scannerWithString:aString];
NSCharacterSet *characterSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSString *output = nil;
[scanner scanUpToCharactersFromSet:characterSet intoString:&output];
但执行后输出字符串为nil。这个代码怎么了?
答案 0 :(得分:2)
您可以使用正则表达式匹配行开头的所有空格(\ s *)(^):
NSString *string = @"\n \n \n This is my string ";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:@"^\\s*" options:0 error:NULL];
NSTextCheckingResult *match = [expression firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
NSString *output = [string substringWithRange:match.range];