Monday, February 7, 2011

Searching text with 'Match case' and 'Match whole word' in file in C++ or Java

Hi. I need a solution in C++ or Java. Are there standard functions?

  • There are no standard functions to do this in C++ - you need to roll your own. This apparent lack is because the concept of uppercase and lowercase, and indeed of words, is a lot more complicated than it might first seem. Your best bet is to use a regular expression library, such as the one that comes with Boost.

    From anon
  • For Java, see Pattern. You can use \b and \B to match word boundaries. Case sensitivity can be enabled/disabled using the CASE_INSENSITIVE flag.

  • There's no single function that will do exactly that. It's still fairly trivial for simple cases: get the file in memory (e.g. std::vector<char> buff(file_begin_iter, file_end_iter);) and then find what you want. (std::search)

    From MSalters
  • In C++ you can use regular expressions in

    std::tr1::regex
    

    if your compiler is up to date. Regular expressions support match case by default. Using \b Word boundaries you should be able to find whole words only.

    anon : Note there is no requirement that a compiler support TR1. A compiler may be "up to date" without doing so.
    RED SOFT ADAIR : You are right writing it "may". In many cases no TR1 implementation is installed with older compilers.
  • In java: http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html

    You can use the "\b" word boundary.

    P.S.: when you compile it remeber scape the slash: In ex.: To found the word 'dog' --> Pattern p = Pattern.compile("\bdog\b");

    From chk

0 comments:

Post a Comment