正規表現でIPアドレス判定ーC言語ーその6
なかなか目的のことをできるようにならない。正規表現でIPアドレス判定ーC言語ーその5 - Shammerismで、文字列として判定されているためではないかと思ったので、それを試してみることに。実装は以下。
#include <ctype.h> #include <regex.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int checkdigit(char *v){ int len = strlen(v); int i; int result = 1; for(i = 0; i < len && result ; i++){ result = isdigit(v[i]); } return result; } int main(int argc, char* args[]){ if( argc == 2 ){ if( checkdigit(args[1]) ){ regex_t preg; int regcompresult; regcompresult = regcomp(&preg, "/^(\\d|[01]?\\d\\d|2[0-4]\\d|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 not digit.\n", args[1]); } } else { printf("%s is required only 1 argument.\n", args[0]); printf("Usage: %s $1\n", args[0]); } return 0; }
実行結果は以下。
$ gcc regex-sample-4.c $ ./a.out 192 192 is not valid. $ ./a.out aaa aaa is not digit. $ ./a.out 255 255 is not valid. $ ./a.out 99999 99999 is not valid. $
文字列もはじくようになったので精度は上がるはずだが、やっぱりダメだ。そもそも使い方を間違えているのだろうか。他の考えられることを試してみるか。