c++ - 匹配不区分大小写的整个字符串

标签 c++ string stl string-matching

我正在寻找一个可以匹配整个单词的函数,例如:

std::string str1 = "I'm using firefox browser";
std::string str2 = "The quick brown fox.";
std::string str3 = "The quick brown fox jumps over the lazy dog.";

只有 str2str3 应该匹配单词 fox。因此,无论单词前后是否有句点(.)或逗号(,)之类的符号,它都应该匹配,同时还必须不区分大小写。

我找到了很多搜索不区分大小写的字符串的方法,但我想知道如何匹配整个单词。

最佳答案

我想推荐 C++11 的 std::regex。但是,它还不适用于 g++4.8。所以我建议替换 boost::regex

#include<iostream>
#include<string>
#include<algorithm>
#include<boost/regex.hpp>

int main()
{
    std::vector <std::string> strs = {"I'm using firefox browser",
                                      "The quick brown fox.",
                                      "The quick brown Fox jumps over the lazy dog."};
    for( auto s : strs ) {
        std::cout << "\n s: " << s << '\n';
        if( boost::regex_search( s, boost::regex("\\<fox\\>", boost::regex::icase))) {
            std::cout << "\n Match: " << s << '\n';
        }
    }
    return 0;
}

/*
    Local Variables:
    compile-command: "g++ --std=c++11 test.cc -lboost_regex -o ./test.exe && ./test.exe"
    End:
 */

输出是:

 s: I'm using firefox browser

 s: The quick brown fox.

 Match: the quick brown fox.

 s: The quick brown Fox jumps over the lazy dog.

 Match: the quick brown fox jumps over the lazy dog.

关于c++ - 匹配不区分大小写的整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25622754/

相关文章:

c++ - 用于定期调用函数的 QTimer 的非空闲替代方案

string - 在 Ada 中打印出字符

java - java中读取和写入数据到文件中,数据中带有双引号

c++ - STL或范围算法有效地找到满足谓词的n个连续元素

c++ - 如何在映射中插入值以列表对?

c++ - 有什么方法比使用 istream eof 更好地读取文件直到文件结束?

c++ - 在 C++ 中发出 REST 请求和解析 REST 响应?

c++ - CMake 无法找到 mysqlclient 库

php - mysql_real_escape_string 无法转义特殊字符,因为文本来自文本编辑器

c++ - 指向成员字段的指针的适配器