【问题标题】:Clarification on regular expression matching for logical AND and OR with Boost使用 Boost 澄清逻辑 AND 和 OR 的正则表达式匹配
【发布时间】:2013-11-22 00:49:27
【问题描述】:

我需要使用正则表达式匹配两种类型的字符串:

//Look for "keyboard" AND "mouse"
(?=.*keyboard)(?=.*mouse)

//Look for "keyboard" OR "mouse"
(keyboard)|(mouse)

我使用 Boost 库运行此代码:

static const boost::regex e("(?=.*keyboard)(?=.*mouse)");
string chat_input("keyboard & mouse");
boost::match_results<std::string::const_iterator> results;
if (boost::regex_match(chat_input, results, e))
{
    //Got a match
}

两个正则表达式都返回no match。我是否使用了错误的语法?

【问题讨论】:

    标签: c++ regex windows boost


    【解决方案1】:

    boost::regex_match 默认是完全匹配,所以你可以使用这个正则表达式".*(keyboard|mouse).*" 来匹配字符串。或者你可以再传递一个参数让它进行部分匹配。

    boost::regex_match(chat_input, results, e, boost::match_default | boost::match_partial)
    

    http://www.boost.org/doc/libs/1_55_0/libs/regex/doc/html/boost_regex/ref/regex_match.html

    "算法regex_match判断给定的正则表达式是否匹配由一对双向迭代器表示的给定字符序列的all,算法定义如下,该函数的主要用途是数据输入验证。”

    http://www.boost.org/doc/libs/1_55_0/libs/regex/doc/html/boost_regex/partial_matches.html

    【讨论】:

    • 我应该改用boost::regex_search,它会起作用的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多