正規表現でIPアドレス判定ーC言語ーその11
正規表現でIPアドレス判定ーC言語ーその10 - Shammerismの続き。0 から 255 までであればOKとする正規表現。
#include <ctype.h> #include <regex.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* args[]){ if( argc == 2 ){ regex_t preg; int regcompresult; regcompresult = regcomp(&preg, "^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$", REG_NOSUB | REG_EXTENDED | REG_NEWLINE); if( regcompresult == 0 ){ size_t nmatch = 0; regmatch_t pmatch[nmatch]; int regexecresult; regexecresult = regexec(&preg, args[1], nmatch, pmatch, 0); if( regexecresult == 0 ){ printf("%s is valid.\n", args[1]); } else { printf("%s is not valid.\n", args[1]); } } else { printf("Regular Expression compile failed.\n"); } } else { printf("%s is required only 1 argument.\n", args[0]); printf("Usage: %s $1\n", args[0]); } return 0; }
実行結果は以下の通り。
$ ./a.out 0 0 is valid. $ ./a.out 01 01 is not valid. $ ./a.out 201 201 is valid. $ ./a.out 255 255 is valid. $ ./a.out 256 256 is not valid. $ ./a.out 1 1 is valid. $ ./a.out 155 155 is valid. $ ./a.out 15a5 15a5 is not valid. $ ./a.out a6 a6 is not valid. $
次は、ドットを含めてやればいい。正規表現の文字列が長くなってしまうが。