bastelhalde.de


Ben,

Regular Expressions in C

Hi, sorry for the long silence. I am currently working on a programming project involving a database where I need to check if user input matches a given date format (yyyy-mm-dd). As simple as it sounds it took me almost an hour to get the regular expression formated until the system finally did what it is supposed to do! So I decided to write it down in case someone has the same issue. First of all, there is regular expression functionality in C you can use on any POSIX system out of the box. But what about the syntax? I wanted to use this simple RegEx for the dates:

#define REGEX_DATE "20[0-9][0-9]-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"

This does not work - always no match although the RegEx itself compiles. After some research I found this document. So it seems you have to backslash-escape every control character (like '(', '|' but not '[' or ']'). So it will be two backslashes until everything works (one backslash makes the compiler think we want to insert some kind of special character).

#define REGEX_DATE "20[0-9][0-9]-\\\\(0[1-9]\\\|1[012]\\\\)-\\\\(0[1-9]\\\|[12][0-9]\\\|3[01]\\\\)"

And finally it works :)


Leave Comment: