Jak używać wyrażeń regularnych w C?

Jak używać wyrażeń regularnych w C?

Możesz użyć PCRE:

Zobacz pcredemo.c, aby zapoznać się z przykładem PCRE.

Jeśli nie możesz użyć PCRE, obsługa wyrażeń regularnych POSIX jest prawdopodobnie dostępna w twoim systemie (jak zauważył @tinkertim). W systemie Windows możesz użyć pakietu gnuwin Regex for Windows.

regcomp dokumentacja zawiera następujący przykład:

#include <regex.h>

/*
 * Match string against the extended regular expression in
 * pattern, treating errors as no match.
 *
 * Return 1 for match, 0 for no match.
 */

int
match(const char *string, char *pattern)
{
    int    status;
    regex_t    re;

    if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
        return(0);      /* Report error. */
    }
    status = regexec(&re, string, (size_t) 0, NULL, 0);
    regfree(&re);
    if (status != 0) {
        return(0);      /* Report error. */
    }
    return(1);
}

Jeśli zostaniesz zmuszony tylko do POSIX (bez pcre), oto ciekawostka:

#include <regex.h>
#include <stdbool.h>

bool reg_matches(const char *str, const char *pattern)
{
    regex_t re;
    int ret;

    if (regcomp(&re, pattern, REG_EXTENDED) != 0)
        return false;

    ret = regexec(&re, str, (size_t) 0, NULL, 0);
    regfree(&re);

    if (ret == 0)
        return true;

    return false;
}

Możesz to nazwać tak:

int main(void)
{
   static const char *pattern = "/foo/[0-9]+$";

   /* Going to return 1 always, since pattern wants the last part of the
    * path to be an unsigned integer */
   if (! reg_matches("/foo/abc", pattern))
       return 1;

   return 0;
}

bardzo zalecam korzystanie z PCRE, jeśli jest dostępny. Ale fajnie jest to sprawdzić i trochę się wycofać.

Pobrałem fragmenty z projektu aktualnie w moim edytorze. To tylko bardzo prosty przykład, ale zawiera typy i funkcje do wyszukania w razie potrzeby. Ta odpowiedź w mniejszym lub większym stopniu uzupełnia odpowiedź Sinana.