在c++中使用正则表达式时出现错误

getting error using regex in C++

本文关键字:错误 正则表达式 c++      更新时间:2023-10-16

给定输入有4行,我应该找出有多少行有word hacker

4
I love #hacker
I just scored 27 points in the Picking Cards challenge on #Hacker
I just signed up for summer cup @hacker
interesting talk by hari, co-founder of hacker

答案是4,但我得到它是0。

int main() {
    int count = 0,t;
    cin >> t;
    string s;
    bool ans;
    while(t--){
        cin >> s;
        smatch sm;
        regex rgx("hacker",regex_constants::icase);
        ans = regex_match(s,sm,rgx);
        if(ans){
            count += 1;
        }         
    }
    cout << ans << endl;
    return 0;
}
  1. 你的while循环只运行t次,每次它只读取一个单词。所以你的程序现在将只读取前三个单词,然后终止。

  2. 你只匹配了整个单词。在#hacker@hacker的情况下,没有匹配

  3. 我相信你想在最后计算count而不是ans

您应该使用std::getline来读取字符串(包含空格)。此外,您应该使用std::regex_search来搜索'部分'匹配(std::regex_match只会在regex匹配整个字符串时匹配)。

你的代码稍微修改了一下:

#include <regex>
#include <iostream>
#include <string>
int main() {
    int count = 0,t;
    std::cin >> t;
    std::string s;
    std::smatch sm;
    std::regex rgx("hacker", std::regex_constants::icase);
    for(int i = 0; i < t; ++i)
    {
        std::getline(std::cin, s);
        while(std::regex_search(s, sm, rgx))
        {  
            ++count;
            s = sm.suffix().str();
        }
    }
    std::cout << count << std::endl;
    return 0;
}

如果您按照以下方式更改正则表达式,您将得到预期的结果:

regex rgx("(.*)hacker(.*)",regex_constants::icase);

它比较的是整个字符串的匹配

否则你必须使用std::regex_search来代替std::regex_match

ans = regex_search(s,sm,rgx);

演示:http://coliru.stacked-crooked.com/a/f28c2e4b315f6f0a

看起来第一个单词应该是输入的行数。但是,尽管看起来您想处理四行输入,但输入显示3 . 问题已被编辑。

你读的不是行,而是字符串,可以翻译成单独的单词。使用getline()获取一行输入

while(t--){
    std::getline(std::cin, s);
    //...

正则表达式格式错误。只有当一行只包含单词"hacker"时,它才会匹配。你想看看hacker是否在这行,所以让你的模式匹配"hacker"周围的其余部分。

    regex rgx(".*hacker.*",regex_constants::icase);

当你发出你的答案时,似乎你想发出count,而不是ans