1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pcreを使って正規表現マッチを行う

Last updated at Posted at 2014-12-10

流れ

  1. pcre_compile() で条件をコンパイルする
  2. pcre_exec() で比較する
  3. pcre_free() でコンパイルした条件を解放

同じ条件で比較を繰り返すならば、pcre_compileを一回だけ行いpcreオブジェクトを共有すれば実行効率が良い

パターンが正しくない時はpcre_compile()はNULLを返す
errStrにエラーメッセージが入る

使用済になったオブジェクトはpcre_freeで必ず解放すること

ソースコード

pcre_match.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pcre.h>

int
pcre_match(const char *subj, char *pattern)
{
    int matched;
    pcre *re;
    const char* errStr;
    int errOffset;
    int ovector = 0;

    re = pcre_compile(pattern, PCRE_EXTENDED, &errStr, &errOffset, NULL);
    if(re == NULL) {
        fprintf(stderr, "pcre pattern matching compile error: message[%s]\n", errStr);
        return -1;
    }

    matched = pcre_exec(re, NULL, subj, (int)strlen(subj), 0, 0, &ovector, 1);
    pcre_free(re);

    if (matched < 0) {
        return 0;
    }

    return 1;
}

int
main(int argc, char *argv[])
{
    if (pcre_match("http://foobar.example.com/", "(^http|^https)://") == 1) {
        printf("matched\n");
    } else {
        printf("unmatched\n");
    }

    return 0;
}

コンパイル


$  gcc -o pcre_match pcre_match.c -lpcre

詳しい使用方法

オンラインマニュアルを参照


$ man pcre_exec

pcreが持っている関数の一覧


$ man -k pcre
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?