【问题标题】:Want to execute NSString as a formula想要将 NSString 作为公式执行
【发布时间】:2012-06-09 08:04:21
【问题描述】:

我有一个 NSString 对象,其中指定了多个条件,如下所示:

NSString *strFormula1 = @"\"man\" == \"man\" && 1<5 || 12<9";
NSString *strFormula2 = @"\"pac@pac.com\" == \"pac1@pac1.com\" || 9==9 && 8>2 || 2==2";

我想执行 NSString 对象中指定的公式并找出答案为 BOOL。 指定的条件是返回 True 还是 False。

提前致谢:)

【问题讨论】:

    标签: iphone ios nsstring


    【解决方案1】:

    只需像这样使用NSPredicate

    NSString *strFormula1 = @"\"man\" == \"man\" && 1<5 || 12<9";
    NSString *strFormula2 = @"\"pac@pac.com\" == \"pac1@pac1.com\" || 9==9 && 8>2 || 2==2";
    NSString *strFormula3 = @"\"hello\" == \"world\"";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:strFormula1];
    BOOL result = [predicate evaluateWithObject:nil]; //True
    
    predicate = [NSPredicate predicateWithFormat:strFormula2];
    result = [predicate evaluateWithObject:nil]; //True
    
    predicate = [NSPredicate predicateWithFormat:strFormula3];
    result = [predicate evaluateWithObject:nil]; //False
    

    如果您想知道谓词如何解析您的表达式,只需使用:

    NSLog(@"%@", [predicate predicateFormat]);
    

    在我们的例子中返回:

    ("man" == "man" AND 1 < 5) OR 12 < 9 //1st Expression
    "pac@pac.com" == "pac1@pac1.com" OR (9 == 9 AND 8 > 2) OR 2 == 2 //2nd Expression
    "hello" == "world" //3rd Expression
    

    【讨论】:

    • 在 Objective-C 中将 ==s 从字符串解析为 ==s 可能不是一个好主意,因为这比较的是内存地址,而不是实际的字符串内容。
    • @Stefan 不,谓词不是这样。 See this answer as well
    • @Stefan 另外,内存地址是什么?整个表达式只是一个字符串,我没有在其中传递任何对象...
    • 是的,对不起,我想你是对的......当我在字符串之间看到==s 时,这是一种反射。 :) 那就为你的答案 +1。
    • 我希望在这种情况下有一个 evaluate 方法,而不是 evaluate:nil,但这有效!
    【解决方案2】:

    你需要一个表达式解析器和求值器。

    试试这个: http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm

    【讨论】:

    • 这将是比@rishi 的(-1 对他)更好的答案,因为 Rahul 需要评估“NSString”对象内容的东西,但你指向的东西没有 C执行。只是 PHP 和 Java。不一定是最容易整合到 Objective C 应用程序中的东西。
    • 如果 OP 不想费心实现自己的解析器,那么使用 JavaScriptCore 框架呢?它接受 CFStringRefs(所以 NSStrings 很好),它有一个功能齐全的数学表达式解析器,支持变量等。
    【解决方案3】:

    您需要结合使用方法和强制转换。

    您的第一个论坛是:

    if([@"\"man\"" isEqualToString:@"\"man\""] && 1 < 5 || 12 < 9) {
            //Forumla == TRUE
     }
    

    如果您想将其转换为 BOOL 对象,如 @rishi 所述:

    BOOL strFormula1 = [@"\"man\"" isEqualToString:@"\"man\""] && 1<5 || 12<9;
    

    如果您 only 有要使用的字符串,正如 @qianfg 建议的那样,您需要使用某种形式的正则表达式解析字符串中的整数和字符串以确定您的变量。

    【讨论】:

    • 这仍然没有回答 OP 的问题。
    • OP 的问题措辞不当,很容易得出令人困惑和/或完全错误的答案。 -1 的问题。
    猜你喜欢
    • 2020-07-24
    • 2012-11-22
    • 2019-09-01
    • 2022-06-17
    • 1970-01-01
    • 2023-01-08
    • 2012-11-25
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多