【问题标题】:I`m trying to make regular expression reader function. C++我正在尝试使正则表达式阅读器功能。 C++
【发布时间】:2020-04-22 22:49:50
【问题描述】:

我有几个单词,并希望将这些单词放在向量中,这样我就可以将每个单词作为一个单独的对象进行操作。问题是当我在找到第一个匹配项后使用函数 regexp_search(string,match,regexp) 我试图删除在找到匹配词之前字符串中的所有内容但调用函数 match.suffinx().str() 时返回 emply 字符串它应该从该字符串返回其他单词。

这是我的正则表达式:

std::regex reg("([C-Fc-f]at)");

这是我的功能:

std::vector<string> stringToVector(string str, regex reg){
cout << boolalpha;
vector<string> vec;
smatch match;


while (regex_search(str, match, reg))
{
    vec.push_back(match.str(1));
    str = match.suffix().str();
}
return vec;}

【问题讨论】:

  • 您能否提供一些示例字符串以及要推回向量的预期子字符串?
  • ye 例如我粘贴字符串:“Cat fat rat bat”函数将“Cat”推入向量内部,但之后的匹配后缀等于“”(空字符串)thats why function stops working and doesnt push向量中的“胖”

标签: c++ regex


【解决方案1】:

您的代码似乎没问题。出于测试目的,我首先修改了您的函数以输出结果...

std::vector<std::string> stringToVector(std::string str, std::regex reg) {
    std::vector<std::string> vec;
    std::smatch match;

    while (std::regex_search(str, match, reg))
    {
        std::cout << "Match\n";
        std::cout << "match.str() = " << match.str() << '\n';
        std::cout << "match.suffix() = " << match.suffix() << '\n';

        vec.push_back(match.str());
        str = match.suffix();
        std::cout << "str = " << str << "'\n\n";
    }
    return vec;
}

然后在Main,我打电话给stringToVector并打印了结果...

std::regex reg("([C-Fc-f]at)");

std::vector<std::string> v;
v = stringToVector("Cat fat rat bat", reg);

for (auto itr = v.begin(); itr != v.end(); ++itr)
{
    std::cout << *itr << '\n';
}

这是输出...

Match
match.str() = Cat
match.suffix() =  fat rat bat
str =  fat rat bat'

Match
match.str() = fat
match.suffix() =  rat bat
str =  rat bat'

Cat
fat

【讨论】:

  • 好吧,我试过你写的代码和它的话,问题是当我创建一个字符串并将它粘贴到这个函数中时,我尝试使用流中的标准( std::cin )输入字符串它 dotnt work. Now Im 试图弄清楚通过 std::cin 插入文本和只在代码中写入字符串之间有什么区别......
  • owww 我明白了,我现在感觉太蠢了,答案是当我使用 std::cin 时它会得到单词直到第一个空格符号,这就是为什么它只能得到第一个单词的解决方案只是使用 std::getLine
猜你喜欢
  • 2016-02-08
  • 2015-05-23
  • 2018-07-05
  • 2020-10-29
  • 1970-01-01
  • 2023-04-06
  • 2016-08-31
  • 2015-10-21
  • 1970-01-01
相关资源
最近更新 更多