正则表达式驱动的while循环没有正确循环

时间:2014-03-13 00:37:29

标签: c++ regex

    ifstream infile("somefile.txt");
    char letter;
    infile >> noskipws >> letter;
    string word;
    word = letter;
    while(regex_match(word, regex("[A-Za-z_][A-Za-z0-9_]*", regex_constants::basic))){
        infile >> letter;
        word += letter;
    }
    if(regex_match(word, regex("[A-Za-z_][A-Za-z0-9_]*.", regex_constants::basic))){
        //Do stuff
    }

当我运行此代码并在GDB中观看时,无论infile正在馈送letter的文本文件中的文本是什么,while循环都将执行一次。然后,它将跳过if语句,因为if语句显然返回false。此函数的每次运行都应该word将整个单词保持在infile的当前位置。我的正则表达式在哪里失败?还是别的什么?

一个澄清的例子:一个只包含单词“words failed me”的文本文件,word在函数末尾只包含“wo”。

3 个答案:

答案 0 :(得分:1)

@MowDownJoe - 我相信std::regexboost::regex,但你为什么要玩,分配一个常量并测试regex_match()。如果它工作正常,如果没有,regex在编译的Lang中不起作用。

答案 1 :(得分:1)

我认为你所看到的是std :: regex的错误实现的结果。我尝试使用相同的正则表达式更简单(参见http://ideone.com/xuY2nD):

#include <iostream>
#include <regex>
using namespace std;

int main() {

    string s = "He";
    if (regex_match(s, regex("[A-Za-z_][A-Za-z0-9_]*", regex_constants::basic))) {
        cout << "Match" << endl;
    }

    return 0;
}

并且它不匹配 - 它本应该做的。然后我尝试了相同的东西,但使用boost :: regex,它按预期工作。

从我read gcc版本&lt; 4.9没有工作std :: regex支持。

一些侧面指示:

  • 构建正则表达式实例可能很昂贵 - 你不应该像在你做的那样在循环中进行。实际上如果在程序中多次调用函数并且正则表达式是常量,那么声明一个静态const实例会更好

  • 在任何情况下,如果您只是检查添加到“单词”中的字符而不是重新匹配整个单词,那么您的逻辑会更有效率。您知道到目前为止已添加的字符已匹配,因此无需重新匹配整个字符串。

  • 第二个正则表达式匹配似乎也是多余的 - 如果循环中的第一个正在运行,那么第二个必须匹配

答案 2 :(得分:0)

来自提升文档:

'The algorithm regex_match determines whether a given regular expression matches 
all of a given character sequence'  

如果您的初始word未匹配,则永远不会附加到。{ 因此,while和if都失败了。