objective-c - 如何检查 NSString 格式是否包含与可变参数相同数量的说明符?

标签 objective-c nsstring stringwithformat variadic-functions

为了确保 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/

相关文章:

objective-c - Objective-C : How do i find out if a number is divisible by another number?

iphone - 无论如何要在 Xcode 中查看方法执行时间?

objective-c - 循环遍历特定文本的文本字段中的值

objective-c - stringByAppendingString 和保留困境

ios - StringWithFormat "%.2ld"objc 到 swift

objective-c - 如何显示静态自定义单元格

ios - 如何在 iOS 中使用 NSString 避免过多的 if-else 语句?

ios - NSString 子串检测

iphone - openURL:使用包含格式化 NSString 的 NSURL 不起作用

database - 内存泄漏: How to stop?