为了确保 NSString initWithFormat:arguments:
返回的格式化字符串符合预期,我需要确定是否有与参数相同数量的格式说明符。下面是一个(稍微做作和高度编辑的)示例:
- (void)thingsForStuff:(CustomStuff)stuff, ...
{
NSString *format;
switch (stuff)
{
case CustomStuffTwo:
format = @"Two things: %@ and %@";
break;
case CustomStuffThree:
format = @"Three things: %@, %@, and %@";
break;
default:
format = @"Just one thing: %@";
break;
}
va_list args;
va_start(args, method);
// Want to check if format has the same number of %@s as there are args, but not sure how
NSString *formattedStuff = [[NSString alloc] initWithFormat:format arguments:args];
va_end(args);
NSLog(@"Things: %@", formattedStuff);
}
使用此方法,[self thingsForStuff:CustomStuffTwo, @"Hello", @"World"]
将记录
"Two things: Hello and World"
...但是 [self thingsForStuff:CustomStuffTwo, @"Hello"]
会记录
"Two things: Hello and "
...最好在它发生之前捕获它。
有没有办法计算字符串中的格式说明符,最好是轻量级/廉价的东西?
最佳答案
好吧,我创建了自己的正则表达式,我不知道它是否会捕获所有这些,并且可能最终会发现一些误报,但似乎对我有用:
static NSString *const kStringFormatSpecifiers =
@"%(?:\\d+\\$)?[+-]?(?:[lh]{0,2})(?:[qLztj])?(?:[ 0]|'.{1})?\\d*(?:\\.\\d+)?[@dDiuUxXoOfeEgGcCsSpaAFn]";
您可以使用以下方法计算参数的数量:
NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern: kStringFormatSpecifiers options:0 error:nil];
NSInteger numSpecifiers = [regEx numberOfMatchesInString: yourString options:0 range:NSMakeRange(0, yourString.length)];
关于objective-c - 如何检查 NSString 格式是否包含与可变参数相同数量的说明符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11875331/