【C/C++】正規表現

2863 ワード

まず、標準C/C++では正規表現はサポートされていませんが、Philip HazelのPerl-compatible Regular Expressionライブラリを提供する関数ライブラリもあり、ほとんどのLinuxリリースではこの関数ライブラリがあります.
正規表現を使用すると、簡単にいくつかのステップに分けられます.
1.正規表現のコンパイル
2.照合の実行
3.メモリの解放
まず、正規表現のコンパイル
int regcomp(regex_t *preg, const char *regex, int cflags);
reqcomp()関数は、正規表現を何らかのフォーマットにコンパイルするために使用され、後のマッチングをより効果的にすることができます.
preg: regex_t構造体は、コンパイル後の正規表現を格納するために使用される.
regex:正規表現ポインタを指す;
cflags:コンパイルモード
次の4つのコンパイル・モードがあります.
REG_EXTENDED:より強力な拡張正規表現を使用
REG_ICASE:大文字と小文字を無視
REG_NOSUB:照合後の結果を記憶しない
REG_NEWLINE:改行を認識し、「$」が行末から一致し、「^」が行の先頭から一致するようにします.そうでなければ改行は無視され、テキスト列全体を文字列として処理します.
次に、照合を実行
int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
preg:コンパイルされた正規表現ポインタ;
string:ターゲット文字列;
nmatch:pmatch配列の長さ;
pmatch:構造体配列、一致するテキスト列の位置情報を格納する;
eflags:マッチングモード
一致モードは2種類あります.
REG_NOTBOL:The match-beginning-of-line operator always fails to match  (but see  the  compilation  flag  REG_NEWLINE above). This flag may be used when different portions of a string are passed  to  regexec and the beginning of the string should not be interpreted as the beginning of the line.
REG_NOTEOL:The match-end-of-line operator always fails to  match  (but  see the compilation flag REG_NEWLINE above)
最後に、メモリを解放
void regfree(regex_t *preg);
コンパイルされた正規表現を使用した後、または他の正規表現を再コンパイルする必要がある場合は、この関数を使用して変数を空にする必要があります.
その他、処理エラー
size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);
regcompまたはregexecを実行してエラーが発生した場合、この関数を呼び出してエラー情報を含む文字列を返すことができます.
errcode:regcompおよびregexec関数によって返されるエラー番号.
preg:regcomp関数でコンパイルされた正規表現.この値はNULLです.
errbuf:エラー情報を格納する文字列のメモリ領域を指します.
errbuf_size:bufferの長さを指定します.このエラー情報の長さがこの値より大きい場合、regerror関数は超過した文字列を自動的に遮断しますが、完全な文字列の長さを返します.そこで,エラー文字列の長さを以下の方法で先に得ることができる.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>

int validate_pattern__r(const char *pattern, const char *in_str);

int main(int argc, char **argv)
{
   int  result = -1;
   char patt[] = "^([2-9][0-9]{3}|[1-9][0-9]{4,6}|10000000)$";
   char str[] = "10000000";

   result = validate_pattern__r(patt, str);
   if(0 == result)
   {
      printf("OK, match!
"); } else { printf("NOK, not match!
"); } return 0; } int validate_pattern__r(const char *pattern, const char *in_str) { int l_status = 0; regex_t l_re; printf("pattern: %s
", pattern); printf("in_str: %s
", in_str); regcomp(&l_re, pattern, REG_EXTENDED); l_status = regexec(&l_re, in_str, (size_t)0, NULL, 0); regfree(&l_re); if(0 != l_status) { return -1; } return 0; }