如果我想从NSString @"value:hello World:value"
中获取一个值,我应该使用什么?
我想要的返回值是@"hello World"
.
如果我想从NSString @"value:hello World:value"
中获取一个值,我应该使用什么?
我想要的返回值是@"hello World"
.
Option 1:
NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"
Option 2:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];
不过,对于你这件小事来说,这件事可能有点过头了.
Option 3:
NSString *needle = [haystack componentsSeparatedByString:@":"][1];
这个函数在拆分时创建三个临时字符串和一个array.
所有代码段都假定搜索的内容实际上包含在字符串中.