c++ - Boost 正则表达式在我的代码中没有按预期工作

标签 c++ regex boost

我今天才开始使用 Boost::regex,在正则表达式方面也是一个新手。我一直在使用“The Regulator”和 Expresso 来测试我的正则表达式,并且似乎对我在那里看到的内容感到满意,但是将该正则表达式转移到 boost,似乎并没有达到我想要的效果。任何能帮助我解决问题的建议都将受到欢迎。作为附带问题,是否有任何工具可以帮助我针对 boost.regex 测试我的正则表达式?

using namespace boost;
using namespace std;

vector<string> tokenizer::to_vector_int(const string s)
{
    regex re("\\d*");
    vector<string> vs;
    cmatch matches;
    if( regex_match(s.c_str(), matches, re) ) {
        MessageBox(NULL, L"Hmmm", L"", MB_OK); // it never gets here
        for( unsigned int i = 1 ; i < matches.size() ; ++i ) {
            string match(matches[i].first, matches[i].second);
            vs.push_back(match);
        }
    }
    return vs;
}

void _uttokenizer::test_to_vector_int() 
{
    vector<string> __vi = tokenizer::to_vector_int("0<br/>1");
    for( int i = 0 ; i < __vi.size() ; ++i ) INFO(__vi[i]);
    CPPUNIT_ASSERT_EQUAL(2, (int)__vi.size());//always fails
}

更新(感谢 Dav 帮助我澄清我的问题): 我希望得到一个包含 2 个字符串的 vector =>“0”和“1”。相反,我从未获得成功的 regex_match()(regex_match() 始终返回 false),因此 vector 始终为空。

感谢'1800 INFORMATION'的建议。 to_vector_int() 方法现在看起来像这样,但它进入了一个永无止境的循环(我采用了您提供的代码并对其进行了修改以使其可编译)并找到“0”,“”,” “,““等等。它永远找不到“1”。

vector<string> tokenizer::to_vector_int(const string s)
{
    regex re("(\\d*)");
    vector<string> vs;

    cmatch matches;

    char * loc = const_cast<char *>(s.c_str());
    while( regex_search(loc, matches, re) ) {
        vs.push_back(string(matches[0].first, matches[0].second));
        loc = const_cast<char *>(matches.suffix().str().c_str());
    }

    return vs;
}

老实说,我认为我还不了解搜索模式和获得匹配项的基础知识。是否有任何带有示例的教程对此进行解释?

最佳答案

基本问题是您在应该使用 regex_search 时使用了 regex_match:

The algorithms regex_search and regex_match make use of match_results to report what matched; the difference between these algorithms is that regex_match will only find matches that consume all of the input text, where as regex_search will search for a match anywhere within the text being matched.

From the boost documentation .将其更改为使用 regex_search 即可。

此外,您似乎没有捕获匹配项。尝试将正则表达式更改为:

regex re("(\\d*)");

或者,您可能需要重复调​​用 regex_search:

char *where = s.c_str();
while (regex_search(s.c_str(), matches, re))
{
  where = m.suffix().first;
}

这是因为您的正则表达式中只有一个捕获。

或者,如果您知道数据的基本结构,请更改您的正则表达式:

regex re("(\\d+).*?(\\d+)");

这将匹配搜索字符串中的两个数字。

请注意,正则表达式\d* 将匹配零个或多个数字 - 这包括空字符串 "",因为这恰好是零个数字。我会将表达式更改为\d+ ,它将匹配 1 个或多个。

关于c++ - Boost 正则表达式在我的代码中没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1269325/

相关文章:

c++ - clang 等同于 -rdynamic gcc 标志是什么?

c++ - 程序不适用于大于 1000 的数字

python re.findall 奇怪的行为

python - 可被 3 整除的正则表达式过滤器编号

boost - 根据 typedef 可以是 wcout 的通用 cout

c++ - 指向堆中定义的对象的多个指针

c++ - 获取指向基类的 protected 方法的指针并将其传递给不同的类

regex - 如何使用 AWK 将带逗号的字段括在引号中?

c++ - Boost::Ubuntu 上的系统链接错误

sockets - Boost 在 SSL 和 TLS 之间进行选择