使用std :: regex进行简单的RX是不错的做法?

时间:2012-04-16 07:22:50

标签: c++ regex

例如,我的情况:
我收到“0”,“1”,“true”或“false”的输入。 (无论如何)
在性能,代码阅读,任何基本最佳实践方面,首选是什么:

bool func(string param)
{
    string lowerCase = param;
    to_lower(lowerCase);
    if (lowerCase == "0" || lowerCase == "false")
    {
        return false;
    }
    if (lowerCase == "1" || lowerCase == "true")
    {
        return true;
    }
    throw ....
}

或:

bool func(string param)
{
    string lowerCase = param;
    to_lower(lowerCase);
    regex rxTrue  ("1|true");
    regex rxFalse ("0|false");

    if (regex_match(lowerCase, rxTrue)
    {
        return true;
    }
    if (regex_match(lowerCase, rxFalse)
    {
        return false;
    }
    throw ....
}

2 个答案:

答案 0 :(得分:3)

第二个更清晰,更容易扩展(例如:接受 "yes""no"或前缀与"1|t(?:rue)?)"和。{ "0|f(?:alse)?"。关于性能,第二个可以(和 应该)通过声明regex static明显加快 (和const,当你在它时),例如:

static regex const rxTrue ( "1|true" , regex_constants::icase );
static regex const rxFalse( "0|false", regex_constants::icase );

另请注意,通过指定不区分大小写,您不必这样做 将输入转换为小写。

答案 1 :(得分:1)

这只是预感,但可能第一个会更快(不涉及正则表达式编译)。此外,第二个版本取决于您的编译器支持C ++ 11 <regex>实现,因此根据您需要支持的环境,第二个选项会自动排除。

相关问题