您应该使用NSRegularExpression的matchesInString:options:range:方法。
返回值
一组NSTextCheckingResult对象。每个结果
通过其 range 属性给出整体匹配范围,并通过其 rangeAtIndex: 方法给出每个单独捕获组的范围。如果捕获组之一未参与此特定匹配,则返回范围 {NSNotFound, 0}。
您可能有如下代码:
NSString *str = @"|You| will |achieve| everything you |want| if you |work| hard";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
@"[^|]*" options: 0 error:nil];
NSArray *results = [regex matchesInString:str
options:0
range:NSMakeRange(0, [str length])];
// ... do interesting code on results...
// Note that you should iterate through the array and use the 'range' property
// to get the range.
for (NSTextCheckingResult *textResult in results)
{
if (textResult.range.length > 0)
{
NSString *substring = [myStr substringWithRange:textResult.range];
NSLog(@"string at range %@ :: \"%@\"",
NSStringFromRange(textResult.range),
substring);
}
}
日志:
{1, 3} :: "You" 范围内的字符串
{5, 6} 范围内的字符串 :: " will "
范围 {12, 7} :: "achieve" 的字符串
{20, 16} 范围内的字符串 :: “你的一切”
{37, 4} :: "want" 范围内的字符串
范围 {42, 8} :: " if you " 的字符串
{51, 4} :: "work" 范围内的字符串
{56, 5} :: "hard" 范围内的字符串