【问题标题】:Case Sensitive Partial Match with Boost's Regex与 Boost 的正则表达式区分大小写的部分匹配
【发布时间】:2009-04-15 10:47:30
【问题描述】:

从下面的代码中,我希望从相应的输入中得到这个输出:

Input: FOO     Output: Match
Input: FOOBAR  Output: Match
Input: BAR     Output: No Match
Input: fOOBar  Output: No Match

但为什么输入 FOOBAR 会给出“不匹配”?

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;


int main  ( int arg_count, char *arg_vec[] ) {
   if (arg_count !=2 ) {
       cerr << "expected one argument" << endl;
       return EXIT_FAILURE;
   }

   string InputString = arg_vec[1];
   string toMatch = "FOO";

   const regex e(toMatch);
   if (regex_match(InputString, e,match_partial)) {
       cout << "Match" << endl;
   } else {
       cout << "No Match" << endl;
   }


   return 0;
}

更新:

最后它适用于以下方法:

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;

bool testSearchBool(const boost::regex &ex, const string st) {
    cout << "Searching " << st << endl;
    string::const_iterator start, end;
    start = st.begin();
    end = st.end();
    boost::match_results<std::string::const_iterator> what;
    boost::match_flag_type flags = boost::match_default;
    return boost::regex_search(start, end, what, ex, flags);
}


int main  ( int arg_count, char *arg_vec[] ) {
    if (arg_count !=2 ) {
        cerr << "expected one argument" << endl;
        return EXIT_FAILURE;
    }

    string InputString = arg_vec[1];
    string toMatch = "FOO*";

    static const regex e(toMatch);
    if ( testSearchBool(e,InputString) ) {
        cout << "MATCH" << endl;
    }
    else {
         cout << "NOMATCH" << endl;
    }

    return 0;
}

【问题讨论】:

    标签: c++ regex boost


    【解决方案1】:

    使用regex_search 代替regex_match

    【讨论】:

      【解决方案2】:

      您的正则表达式必须考虑子字符串“FOO”开头和结尾的字符。 我不确定,但“FOO*”可能会起作用

      match_partial 仅当部分字符串位于文本输入的末尾而不是开头时才返回 true。

      部分匹配是匹配的 结尾的一个或多个字符 文本输入,但不匹配所有 的正则表达式(虽然它 如果有更多的输入,可能已经这样做了 可用)

      所以与“FOO”匹配的 FOOBAR 将返回 false。 正如另一个答案所暗示的,使用 regex.search 可以让您更有效地搜索子字符串。

      【讨论】:

      • @Gayan:我试过了,字符串 toMatch = "FOO*";还是不匹配。
      • 这只是一种预感。我没有使用 boost 编写测试应用程序的奢侈。对不起
      • 这不是外壳扩展。 “FOO*”将是一个“F”,后跟一个“O”,然后是零个或多个“O”。
      • 是的。我是这么想的。我不太记得正则表达式。 FOO[a-z]*[A-Z]*?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多