Shammer's Philosophy

My private adversaria

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

正規表現でIPアドレス判定ーC言語ーその8 - Shammerismで、数字一桁の正規表現に成功。
次のステップとして、1 から 99 までの場合に OK となるような正規表現を考える。
十の位が 0 になることはないので、一桁の正規表現に"OR"を追加する形で実現させる。

#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 9
9 is valid.
$ ./a.out 99
99 is valid.
$ ./a.out 990
990 is not valid.
$ ./a.out 19
19 is valid.
$ ./a.out 09
09 is not valid.
$ ./a.out 25
25 is valid.
$ ./a.out 2523
2523 is not valid.
$ ./a.out aaxx
aaxx is not valid.
$ ./a.out a2
a2 is not valid.
$ ./a.out 6a
6a is not valid.
$ ./a.out 10
10 is valid.
$

期待通りの結果を得られた。ただ、行頭と行末記号が二つになってしまった。
次は、これを一つにできないかを検討する。