我正在寻找一个可以匹配整个单词的函数,例如:
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.";
只有 str2
和 str3
应该匹配单词 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/