Shammer's Philosophy

My private adversaria

正規表現でIPアドレス判定ーC言語ーその5

正規表現でIPアドレス判定ーC言語ーその4 - Shammerismの続き。大ボケかましていたので仕切り直しで再実装。以下のコードを試す。

#include <regex.h>
#include <stdio.h>

int main(int argc, char* args[]){
    if( argc == 2 ){
	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 required only 1 argument.\n", args[0]);
	printf("Usage: %s $1\n", args[0]);
    }
    return 0;
}

実行結果は以下。

$ gcc regex-sample-3.c
$ ./a.out 192
192 is not valid.
$ ./a.out 127
127 is not valid.
$ ./a.out aaa
aaa is not valid.
$ ./a.out 256
256 is not valid.
$

やっぱりダメだ。256 や aaa を valid にしてしまうのであれば、判定結果が逆とかいう(自分からしても)単純な結果になるが・・・どこかまだおかしい感じだ。フラグと行頭行末の正規表現なしでやってみるか。あと、文字列として判定されている可能性が考えられる。