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

Matching a whole string with case insensitive

本文关键字:字符串 大小写 不区      更新时间:2023-10-16

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

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.";

对于单词fox,只有str2str3应该匹配。因此,单词前后是否有句点(.)或逗号(,)这样的符号并不重要,它应该匹配,同时它还必须是不区分大小写的搜索。

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

我想推荐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.