【发布时间】: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,程序就会永远挂起!无响应的界面,没有错误,没有false 或true!为什么?
我正在 OpenSuse 最新版本下使用 KDevelop 进行开发。
【问题讨论】:
-
@JesperJuhl 这不符合我使用正则表达式的经验。
-
@JesperJuhl 他说它会无限期地挂起他的程序。
-
我看不出正则表达式有什么可疑之处;没有循环,没有歧义,没有潜在的重叠匹配。
-
所以你有问题。你会想,“我知道,我可以用正则表达式解决它!”。现在你有两个问题;原来的问题,你正在使用正则表达式。