【问题标题】:Is there a format string parser for NSString?NSString 有格式字符串解析器吗?
【发布时间】:2012-10-09 11:16:39
【问题描述】:

我想使用+stringWithFormat:… 中的格式字符串解析字符串。打印和解析具有相同格式字符串的字符串会非常方便。只需要一个本地化的。

例子:

NSString *format = @"His name is \"%@\"";
NSString *string = [NSString stringWithFormat:format, @"Bob"];
NSArray *array = [string parseWithFormat:format];

array 应该返回 @[@"Bob"]。有没有这样一个开源项目试图做到这一点?我认为应该可以将这样的格式字符串转换为正则表达式。

【问题讨论】:

    标签: iphone cocoa parsing nsstring


    【解决方案1】:

    stringWithFormat“只是”sprintf 的前端;因为它是纯 C 语言,scanf 及其变体也可以根据需要提供。

    【讨论】:

    • 好推荐。采用 Cocoa 并非易事,因为还有 %@
    • 将所有 NSString 转换为 C 字符串,一切顺利。
    【解决方案2】:

    您描述parseWithFormat 函数的方式,由于结构模糊,它无法工作。

    用于格式替换的%@ 标记已在您的结果字符串string 中消失,因此生成的提取结果可能不明确。

    例子

    NSString *format = @"He likes %@ and %@.";
    NSString *string = [NSString 
       stringWithFormat:format, @"apples and oranges", @"bananas"];
    // --> @"He likes apples and oranges and bananas."
    NSArray *array = [string parseWithFormat:format];
    // Array could be:
    // @[@"apples and oranges", @"bananas"] or 
    // @[@"apples"  @"oranges and bananas"]
    

    【讨论】:

    • 解析器总是要处理歧义。正则表达式也是如此。我会接受的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多