Shammer's Philosophy

My private adversaria

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

正規表現でIPアドレス判定ーC言語ーその9 - Shammerismで、数字二桁の正規表現に成功。
だが、行頭と行末記号を二度含む表現になってしまったので、これを一つずつにする正規表現を考える。
括弧を使用すればいいと思うのだがどうだろうか。。

#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])$", 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 99
99 is valid.
$ ./a.out 99000
99000 is not valid.
$ ./a.out 9
9 is valid.
$ ./a.out 10
10 is valid.
$ ./a.out 1
1 is valid.
$ ./a.out 100
100 is not valid.
$ ./a.out 1a
1a is not valid.
$ ./a.out a1
a1 is not valid.
$ ./a.out aa
aa is not valid.
$

問題なし。次は 1 から 200 までの正規表現にするか。
でもこうした場合は 260 とか 256 以上の値を NG にするのが面倒なことになりそう。
1 から 199 まで、200 から 249 まで、250 から 255 までに分けるのがよさそうだ。