shybovycha
shybovycha

Reputation: 12245

GCC regular expressions

How do I use regular expressions in GNU G++ / GCC for matching, searching and replacing substrings? E.g. could you provide any tutorial on regex_t and others?

Googling for above an hour gave me no understandable tutorial or manual.

Upvotes: 3

Views: 7169

Answers (3)

shybovycha
shybovycha

Reputation: 12245

I found the answer here:

#include <regex.h>
#include <stdio.h>

int main() 
{
  int r;
  regex_t reg;

  if (r = regcomp(&reg, "\\b[A-Z]\\w*\\b", REG_NOSUB | REG_EXTENDED)) 
  {
    char errbuf[1024];

    regerror(r, &reg, errbuf, sizeof(errbuf));
    printf("error: %s\n", errbuf);

    return 1;
  }

  char* argv[] = { "Moo", "foo", "OlOlo", "ZaooZA~!" };

  for (int i = 0; i < sizeof(argv) / sizeof(char*); i++) 
  {
    if (regexec(&reg, argv[i], 0, NULL, 0) == REG_NOMATCH)
      continue;

    printf("matched: %s\n", argv[i]);
  }

  return 0;
}

The code above will provide us with

matched: Moo 
matched: OlOlo 
matched: ZaooZA~!

Upvotes: 4

Dan Vatca
Dan Vatca

Reputation: 321

I strongly suggest using the Boost C++ regex library. If you are developing serious C++, Boost is definitely something you must take into account.

The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right.

http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html

But if you don't have any knowledge of this fine library, I suggest you start here:

http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html

Upvotes: 4

unwind
unwind

Reputation: 399813

Manuals should be easy enough to find: POSIX regular expression functions. If you don't understand that, I would really recommend trying to brush up on your C and C++ skills.

Note that actually replacing a substring once you have a match is a completely different problem, one that the regex functions won't help you with.

Upvotes: 2

Related Questions