【问题标题】:Regex matching takes forever正则表达式匹配需要永远
【发布时间】:2018-02-12 19:19:44
【问题描述】:

我有一个30行左右的简单文本文件,如下:

A 45.0 X 250.0  
Y -23.8
A 22.0 X -1016.0
Y 4.9
L 0
M 16.1 T 0 N 0

...etc...
...etc...

每行包含 1 到 3 对大写字母和浮点数。所有分隔符都是空格。
然后我做了一个程序,用这个简单的正则表达式检查该文件的每一行:

std::ifstream stream;
try
{
    stream.open("/ArchivioProgrammi/p1.prg", std::ios::in);
}
catch(std::exception& e)
{
    std::stringstream st;
    st << "Error opening file.\nError:   " << e.what();
    throw MyLoadException(st.str());
}
std::string line;
unsigned int lineCount = 0;

while(std::getline(stream, line))  //  Per ogni linea del file estraggo fino a 6 token
{
    if(line.length() == 0) continue;

    /***  This "if" hangs indefinitely!!  ***/
    if(!std::regex_match(line, std::regex("([A-Z] [\\-\\+]?[0-9]+(\\.[0-9]+)?)( [A-Z] [\\-\\+]?[0-9]+(\\.[0-9]+)?){0,2}")))
    {
        std::stringstream st;
        st << "Line #" << lineCount << " is invalid.";
        throw MyLoadException(st.str());
    }

    //  Tokenize the line and do something with the tokens...

    ++lineCount;

}

if(stream.eof())
{
    stream.close();
}

只要控件到达if,程序就会永远挂起!无响应的界面,没有错误,没有falsetrue!为什么?

我正在 OpenSuse 最新版本下使用 KDevelop 进行开发。

【问题讨论】:

  • @JesperJuhl 这不符合我使用正则表达式的经验。
  • @JesperJuhl 他说它会无限期地挂起他的程序。
  • 我看不出正则表达式有什么可疑之处;没有循环,没有歧义,没有潜在的重叠匹配。
  • 所以你有问题。你会想,“我知道,我可以用正则表达式解决它!”。现在你有两个问题;原来的问题,你正在使用正则表达式。

标签: c++ regex linux c++11


【解决方案1】:

尝试通过在线测试确认您的正则表达式模式是否正确(例如online Regex tester)。您可能还需要考虑一次使用正则表达式逐行遍历输入文件。或者根本不使用正则表达式。

【讨论】:

  • 我不确定你的建议是什么。一行一行地走?这正是我所说的我正在做的事情!
  • 抱歉 - 我从您的代码中看到您正在逐行阅读。我还测试了您的正则表达式模式,它确实在您的文本文件中找到了匹配项。开始注释你的代码(例如 if(!std::regex_match) 直到你找到导致它挂起的原因。希望你解决它。
【解决方案2】:

使用原始字符串它就像一个魅力。 即使我从来没有理解用双引号和括号开始这样的字符串的含义......

我怎么能把正则表达式写成更短的形式?

【讨论】:

  • 我怎么能把正则表达式写成更短的形式?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多