Home

Awesome

CI

tiny-regex-c

A small regex implementation in C

Description

Small and portable Regular Expression (regex) library written in C.

Design is inspired by Rob Pike's regex-code for the book "Beautiful Code" available online here.

Supports a subset of the syntax and semantics of the Python standard library implementation (the re-module).

I will gladly accept patches correcting bugs.

Design goals

The main design goal of this library is to be small, correct, self contained and use few resources while retaining acceptable performance and feature completeness. Clarity of the code is also highly valued.

Notable features and omissions

API

This is the public / exported API:

/* Typedef'd pointer to hide implementation details. */
typedef struct regex_t* re_t;

/* Compiles regex string pattern to a regex_t-array. */
re_t re_compile(const char* pattern);

/* Finds matches of the compiled pattern inside text. */
int  re_matchp(re_t pattern, const char* text, int* matchlength);

/* Finds matches of pattern inside text (compiles first automatically). */
int  re_match(const char* pattern, const char* text, int* matchlength);

Supported regex-operators

The following features / regex-operators are supported by this library.

NOTE: inverted character classes are buggy - see the test harness for concrete examples.

Usage

Compile a regex from ASCII-string (char-array) to a custom pattern structure using re_compile().

Search a text-string for a regex and get an index into the string, using re_match() or re_matchp().

The returned index points to the first place in the string, where the regex pattern matches.

The integer pointer passed will hold the length of the match.

If the regular expression doesn't match, the matching function returns an index of -1 to indicate failure.

Examples

Example of usage:

/* Standard int to hold length of match */
int match_length;

/* Standard null-terminated C-string to search: */
const char* string_to_search = "ahem.. 'hello world !' ..";

/* Compile a simple regular expression using character classes, meta-char and greedy + non-greedy quantifiers: */
re_t pattern = re_compile("[Hh]ello [Ww]orld\\s*[!]?");

/* Check if the regex matches the text: */
int match_idx = re_matchp(pattern, string_to_search, &match_length);
if (match_idx != -1)
{
  printf("match at idx %i, %i chars long.\n", match_idx, match_length);
}

For more usage examples I encourage you to look at the code in the tests-folder.

TODO

FAQ

License

All material in this repository is in the public domain.