1

I'm looking for a function if available to match a whole word for example:

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

Only str2 and str3 should match for the word fox. So, it doesn't matter if there is a symbol like period (.) or a comma (,) before or after the word and it should match and it also has to be case-insensitive search at the same time.

I've found many ways to search a case insensitive string but I would like to know something for matching a whole word.

cpx
  • 17,009
  • 20
  • 87
  • 142
  • http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – Alessandro Pezzato Sep 02 '14 at 11:55
  • Can you give an example of an invocation of that function, and the expected result? – juanchopanza Sep 02 '14 at 11:56
  • The result can be `bool` to represent if the matching string was found or an index position where it starts just as `std::find` and `std::search` function. – cpx Sep 02 '14 at 12:06
  • There are several ways of doing this, not sure of any STL built-in method but you might code your own with regex support or do some pattern matching (the insensitiveness should be easy to support) – Marco A. Sep 02 '14 at 12:06
  • @cpx You said "match" so I assume this is a regex problem, which makes it trivial. –  Sep 02 '14 at 12:06
  • @remyabel: Would it be different if I say to "search" the whole word in a string with case insensitiveness? – cpx Sep 02 '14 at 12:08

1 Answers1

0

I would like to recommend std::regex of C++11. But, it is not working yet with g++4.8. So I recommend the replacement 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:
 */

The output is:

 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.
Tobias
  • 5,038
  • 1
  • 18
  • 39