tags:

views:

710

answers:

2

Hello. I'm after some simple examples and best practices of how to use regular expressions in ANSI C. Man regex.h does not provide that much help.

Thank you.

+10  A: 

Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C.

Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.

Laurence Gonsalves
Unless you need to avoid the dependency I second PCRE, it has some nice syntax enhancements and is very stable. At least with some older versions of Linux, the "built in" regular expression library isn't too difficult to crash given certain input strings and certain regular expressions that "almost" match or involve a lot of special characters
bdk
A: 

It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.

Michiel Buddingh'