regex.h
C言語で正規表現を使うにはregex.hをincludeします。
具体的に利用する関数はregcomp(), regexec(), regfree()関数の3つです。
regcomp() 関数
- int regcomp(regex_t *preg, const char *regex, int cflags)
- 正規表現のコンパイルを行なう。コンパイル成功時には0を返す。cflags には以下に示す定数一つ以上のビットごとの OR (bitwise-or) を指定する。
- REG_EXTENDED
- regex に POSIX 拡張正規表現を使用する。もしこのフラグが設定されない場合、POSIX 標準正規表現が使われる。
- REG_ICASE
- 大文字小文字の違いを無視する。
- REG_NOSUB
- このフラグを設定してコンパイルされたパターンバッファが regexec の引数に指定されると、パラメータ nmatch, pmatch が無視される。
- REG_NEWLINE
- 全ての文字にマッチするオペレータに改行をマッチさせない。
regexec() 関数
- int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
- 正規表現による検索を実行する。eflags には以下に示す定数一つ以上のビットごとの OR (bitwise-or) を指定する。
- REG_NOTBOL
- 行頭にマッチするオペレータは、必ずマッチに失敗する (コンパイル時のフラグ REG_NEWLINE の項目も参照)。このフラグは、複数行にまたがる文字列を regexec() で検索する際に、文字列の先頭を行の先頭として解釈させない場合に用いる。
- REG_NOTEOL
- 行末にマッチするオペレータは、必ずマッチに失敗する。
regfree()関数
- void regfree(regex_t *preg)
- 正規表現パターンバッファを解放する。
正規表現サンプルコード
カンマ区切りの文字列から、数値を取り出す。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
int main() {
char str[] = "123, 456, 789";
regex_t preg;
size_t nmatch = 5;
regmatch_t pmatch[nmatch];
int i, j;
if (regcomp(&preg, "([[:digit:]]+), ([[:digit:]]+), ([[:digit:]]+)", REG_EXTENDED|REG_NEWLINE) != 0) {
printf("regex compile failed.\n");
exit(1);
}
printf("String = %s\n", str);
if (regexec(&preg, str, nmatch, pmatch, 0) != 0) {
printf("No match.\n");
} else {
for (i = 0; i < nmatch; i++) { /* nmatch にマッチした件数が入る */
printf("Match position = %d, %d , str = ", (int)pmatch[i].rm_so, (int)pmatch[i].rm_eo);
if (pmatch[i].rm_so >= 0 && pmatch[i].rm_eo >= 0) {
for (j = pmatch[i].rm_so ; j < pmatch[i].rm_eo; j++) {
putchar(str[j]);
}
}
printf("\n");
}
}
regfree(&preg);
return 0;
}
実行結果
$ gcc regex-sample.c
$ ./a.out
String = 123, 456, 789
Match position = 0, 13 , str = 123, 456, 789
Match position = 0, 3 , str = 123
Match position = 5, 8 , str = 456
Match position = 10, 13 , str = 789
Match position = -1, -1 , str =
参考文献
参考URL