summaryrefslogtreecommitdiff
path: root/sample/posix.c
blob: 35ccb68d5b59ad6ccf50101adeac4b67dbbf7525 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
 * posix.c
 */
#include <stdio.h>
#include "onigposix.h"

typedef unsigned char  UChar;

static int x(regex_t* reg, unsigned char* pattern, unsigned char* str)
{
  int r, i;
  char buf[200];
  regmatch_t pmatch[20];

  r = regexec(reg, (char* )str, reg->re_nsub + 1, pmatch, 0);
  if (r != 0 && r != REG_NOMATCH) {
    regerror(r, reg, buf, sizeof(buf));
    fprintf(stderr, "ERROR: %s\n", buf);
    regfree(reg);
    return -1;
  }

  if (r == REG_NOMATCH) {
    fprintf(stderr, "FAIL: /%s/ '%s'\n", pattern, str);
  }
  else {
    fprintf(stderr, "OK: /%s/ '%s'\n", pattern, str);
    for (i = 0; i <= (int )reg->re_nsub; i++) {
      fprintf(stderr, "%d: %d-%d\n", i, pmatch[i].rm_so, pmatch[i].rm_eo);
    }
  }
  regfree(reg);
  return 0;
}

extern int main(int argc, char* argv[])
{
  int r;
  char buf[200];
  regex_t reg;
  UChar* pattern;

  reg_set_encoding(REG_POSIX_ENCODING_ASCII);

  /* default syntax (ONIG_SYNTAX_ONIGURUMA) */
  pattern = (UChar* )"^a+b{2,7}[c-f]?$|uuu";
  r = regcomp(&reg, (char* )pattern, REG_EXTENDED);
  if (r) {
    regerror(r, &reg, buf, sizeof(buf));
    fprintf(stderr, "ERROR: %s\n", buf);
    regfree(&reg);
    return -1;
  }
  x(&reg, pattern, (UChar* )"aaabbbbd");

  /* POSIX Basic RE (REG_EXTENDED is not specified.) */
  pattern = (UChar* )"^a+b{2,7}[c-f]?|uuu";
  r = regcomp(&reg, (char* )pattern, 0);
  if (r) {
    regerror(r, &reg, buf, sizeof(buf));
    fprintf(stderr, "ERROR: %s\n", buf);
    regfree(&reg);
    return -1;
  }
  x(&reg, pattern, (UChar* )"a+b{2,7}d?|uuu");

  /* POSIX Basic RE (REG_EXTENDED is not specified.) */
  pattern = (UChar* )"^a*b\\{2,7\\}\\([c-f]\\)$";
  r = regcomp(&reg, (char* )pattern, 0);
  if (r) {
    regerror(r, &reg, buf, sizeof(buf));
    fprintf(stderr, "ERROR: %s\n", buf);
    regfree(&reg);
    return -1;
  }
  x(&reg, pattern, (UChar* )"aaaabbbbbbd");

  /* POSIX Extended RE */
  onig_set_default_syntax(ONIG_SYNTAX_POSIX_EXTENDED);
  pattern = (UChar* )"^a+b{2,7}[c-f]?)$|uuu";
  r = regcomp(&reg, (char* )pattern, REG_EXTENDED);
  if (r) {
    regerror(r, &reg, buf, sizeof(buf));
    fprintf(stderr, "ERROR: %s\n", buf);
    regfree(&reg);
    return -1;
  }
  x(&reg, pattern, (UChar* )"aaabbbbd)");

  pattern = (UChar* )"^b.";
  r = regcomp(&reg, (char* )pattern, REG_EXTENDED | REG_NEWLINE);
  if (r) {
    regerror(r, &reg, buf, sizeof(buf));
    fprintf(stderr, "ERROR: %s\n", buf);
    regfree(&reg);
    return -1;
  }
  x(&reg, pattern, (UChar* )"a\nb\n");

  onig_end();
  return 0;
}