c++ - 在 C++ 中使用正则表达式出错

标签 c++ regex c++11

给定输入有 4 行,我应该找出有多少行有单词 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

关于c++ - 在 C++ 中使用正则表达式出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31252712/

相关文章:

c++ - C++数组指针如何具有不同的位置,但指向相同的元素?

regex - 精确字符串 coldfusion 正则表达式

c++ - std::string 可以为右值 *this 重载 "substr"并窃取资源吗?

c++ - 可移动但不可复制的异常

c++ - 如何在 Boost 中使用元组映射?

java - 如何在 Android 上使用 jni.h?

regex - 为电话号码编写正则表达式

c++ - 原子 bool 无法保护非原子计数器

c++ - 初始化常量的问题

java - 重构模式匹配序列