我正在构建一个小型实用程序方法来解析一行(字符串)并返回所有单词的 vector 。我下面的 istringstream 代码工作正常,除了有标点符号的时候,所以我的解决办法自然是想在通过 while 循环运行它之前“清理”该行。
如果能为此使用 C++ 中的正则表达式库提供一些帮助,我将不胜感激。我最初的解决方案是使用 substr() 并去镇上,但这看起来很复杂,因为我必须迭代和测试每个字符以查看它是什么,然后执行一些操作。
vector<string> lineParser(Line * ln)
{
vector<string> result;
string word;
string line = ln->getLine();
istringstream iss(line);
while(iss)
{
iss >> word;
result.push_back(word);
}
return result;
}
最佳答案
不需要仅仅为了标点符号而使用正则表达式:
// Replace all punctuation with space character.
std::replace_if(line.begin(), line.end(),
std::ptr_fun<int, int>(&std::ispunct),
' '
);
或者如果你想把除了字母和数字以外的所有东西都变成空格:
std::replace_if(line.begin(), line.end(),
std::not1(std::ptr_fun<int,int>(&std::isalphanum)),
' '
);
当我们在这里时:
您的 while 循环已损坏,会将最后一个值插入 vector 两次。
应该是:
while(iss)
{
iss >> word;
if (iss) // If the read of a word failed. Then iss state is bad.
{ result.push_back(word);// Only push_back() if the state is not bad.
}
}
或者更常见的版本:
while(iss >> word) // Loop is only entered if the read of the word worked.
{
result.push_back(word);
}
或者你可以使用 STL:
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter(result)
);
关于c++ - 需要一个正则表达式来仅从字符串中提取字母和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5540008/