yes, virginia, you CAN do regular expressions in C/C++

April 10, 2009

You say you want a regular expression?  Well, you know, you don’t have to install Perl.

There’s a few ways you can go about using regular expressions in your C / C++ code.

  1. The POSIX C regex library.  This presumes of course you are running on a Unix-ish system, e.g. Linux, Mac OSX, iPhone, BSD, etc.
    #include <regex.h>
    regex_t re;
    const char* re_string = "m[Aa]t?ch.*";
    if(regcomp(&re, re_string, REG_NOSUB) != 0){
      std::cerr << "Invalid regular expression" << std::endl;
    if(regexec(&re, "mAchzzzzaaaa!!!!oneone", (size_t)0, NULL, 0) == 0)
      std::cout << "Found a match!" << std::endl;
  2. The Boost Regex POSIX-like API.  This is a C wrapper to the Boost Regex library, which allows you to use the library with POSIX regex calls.
    #include <boost/regex.h>
    // otherwise use just as you would the POSIX lib
  3. The Boost Regex C++ API, straight no chaser.
    #include <boost/regex.hpp>
    boost::regex re("m[Aa]t?ch.*");
    if(boost::regex_match("mAchzzzzaaaa!!!!oneone", re))
      std::cout << "Found a match!" << std::end;

This is but a taste of what’s available.  Peep the POSIX regex API and the Boost Regex Documentation.  Note, Boost Regex is one of only a handful of the Boost packages that needs to be explicitly built and linked with your code.

Leave a Reply