C 正则库 Demo (regex, pcre)
例子为匹配ip地址
pcre库(perl正则)
/* * gcc pcre.c -o pcrec -lpcre */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pcre/pcre.h> int is_match (const char *src, const char *pattern) { pcre *re; const char *error; int erroffset; int result; re = pcre_compile (pattern, /* the pattern */ 0, /* default options */ &error, /* for error message */ &erroffset, /* for error offset */ NULL); /* use default character tables */ /* Compilation failed: print the error message and exit */ if (re == NULL) { printf ("PCRE compilation failed at offset %d: %s\n", erroffset, error); return -1; } result = pcre_exec (re, /* the compiled pattern */ NULL, /* no extra data - we didn't study the pattern */ src, /* the src string */ strlen (src), /* the length of the src */ 0, /* start at offset 0 in the src */ 0, /* default options */ NULL, 0); /* If Matching failed: */ if (result < 0) { free (re); return -1; } free (re); return result; } int main ( int argc, char *argv[] ) { const char *pattern = "^((25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d?\\d)$"; const char *src = "5250.222.0.12"; const char *src1 = "127.0.0.1"; int result = is_match(src, pattern); printf ("%s %s\n", src, result != 0? "not matched":"matched"); result = is_match(src1, pattern); printf ("%s %s\n", src1, result != 0? "not matched":"matched"); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
参考:http://www.cnblogs.com/skillup/articles/1876216.html
标准库demo(posix正则)
/* *gcc regex.c -o regex */ #include <stdio.h> #include <stdlib.h> #include <regex.h> /* * Regular expressions verification * If matched success: return 0 */ int is_match(const char *src, const char *pattern) { regex_t preg; char prbuf[200]; int rc; rc = regcomp(&preg, pattern, REG_EXTENDED); if (rc != 0) { regerror(rc, &preg, prbuf, sizeof(prbuf)); printf("Regex compile error: %s\n", prbuf); } rc = regexec(&preg, src, 0, 0, 0); return rc; } int main ( int argc, char *argv[] ) { const char *pattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])$"; const char *src = "5250.222.0.12"; const char *src1 = "127.0.0.1"; int result = is_match(src, pattern); printf ("%s %s\n", src, result != 0? "not matched":"matched"); result = is_match(src1, pattern); printf ("%s %s\n", src1, result != 0? "not matched":"matched"); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */