2017-09-16 41 views
-1

我试图分析在C++中使用正则表达式的文件的字符串,但是当我从文件中读取字符串,regex_search不工作:C++ 11 regex_search不工作,但regex_match是

string stream; 

    ifstream file("weather.txt"); 
    stream.assign((istreambuf_iterator<char>(file)), 
       (istreambuf_iterator<char>())); 

    const string s = stream; 
    regex rgx("[0-9]{1,2}-[0-9]{1,2}"); 
    smatch match; 

    for(i=0; i < 12; i++){ 
    if (regex_search(s, match, rgx)) 
     cout << "match: " << match[i] << '\n'; 
    } 

但是,如果我做了regex_match(),它的工作原理:

if (regex_match(s, rgx)); 
    cout <<" YEass"; 

我试图用一个简单的字符串和它的工作,但是当我从文件中读取内容它不工作。

回答

0

当您使用regex_search和你期望获得超过1结果
你必须使用迭代器(指针),进入到下一个起始位置
字符串中。

std::string::const_iterator start, end; 
start = s.begin(); 
end = s.end(); 
smatch m; 

while (regex_search(start, end, m, rx)) 
{ 
    // do something with the results 
    std::string sgrp1(m[1].first, m[1].second); 
    std::string sgrp2(m[2].first, m[2].second); 
    std::string sgrp3(m[3].first, m[3].second); 
    // etc, ... 

    // update search position: 
    start = m[0].second; 
} 

什么你实际上做的是试图
12次,以显示个人12组一次一个重新匹配整个字符串,
这是没有办法的办法去。

如果您确实有12组,则只需匹配一次,然后在匹配结果上迭代

if (regex_search(start, end, m, rx)) 
{ 
    for (int i = 0; i < 12; i++) 
    { 
     std::string str(m[i].first, m[i].second); 
     cout << "group " << i << " = " << str << "\r\n"; 
    } 
} 
+0

感谢您的回答,我还无法测试它,但我不太了解第一个示例中的字符串组。每个字符串组都是来自搜索的匹配项? m的第一个和第二个对象究竟是什么?对不起,这是我第一次使用这个正则表达式库,我还不熟悉它。 –

+0

我尝试了两个选项,但regex_search仍然返回错误:( –

+0

_'match_results'_是子表达式匹配的索引集合。_'sub_match'_类型的对象只能通过对类型为match_results的对象进行下标获取。每个sub_match代表一个在正则表达式中定义的_group_,比如'(abc)(def)(ghi)(jk)'有4个组,但是你的正则表达式是[0-9] {1,2 } - [0-9] {1,2}'没有组,事实上,当你尝试在你的循环中通过'm [i]'来索引匹配对象时,它会引发一个运行时错误。 – sln