需要正则表达式才能从字符串中提取字母和空格

Pet*_*ete 1 c++ regex

我正在构建一个小实用程序方法来解析一行(一个字符串)并返回所有单词的向量.我下面的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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 7

不需要仅为标点符号使用正则表达式:

// Replace all punctuation with space character.
std::replace_if(line.begin(), line.end(),
                std::ptr_fun<int, int>(&std::ispunct),
                ' '
               );
Run Code Online (Sandbox Code Playgroud)

或者如果你想要除了字母和数字之外的所有内容都变成空格

std::replace_if(line.begin(), line.end(),
                std::not1(std::ptr_fun<int,int>(&std::isalphanum)),
                ' '
               );
Run Code Online (Sandbox Code Playgroud)

当我们在这里时:
你的while循环被打破并将最后一个值推入向量两次.

它应该是:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

或者更常见的版本:

while(iss >> word) // Loop is only entered if the read of the word worked.
{
    result.push_back(word);
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用stl:

std::copy(std::istream_iterator<std::string>(iss),
          std::istream_iterator<std::string>(),
          std::back_inserter(result)
         );
Run Code Online (Sandbox Code Playgroud)