1 /*
2  * scan.c
3  */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include "onigmo.h"
7 
8 static int
scan_callback(OnigPosition n,OnigPosition r,OnigRegion * region,void * arg)9 scan_callback(OnigPosition n, OnigPosition r, OnigRegion* region, void* arg)
10 {
11   int i;
12 
13   fprintf(stdout, "scan: %ld\n", n);
14 
15   fprintf(stdout, "match at %ld\n", r);
16   for (i = 0; i < region->num_regs; i++) {
17     fprintf(stdout, "%d: (%ld-%ld)\n", i, region->beg[i], region->end[i]);
18   }
19 
20   return 0;
21 }
22 
23 static int
scan(regex_t * reg,unsigned char * str,unsigned char * end)24 scan(regex_t* reg, unsigned char* str, unsigned char* end)
25 {
26   int r;
27   OnigRegion *region;
28 
29   region = onig_region_new();
30 
31   r = onig_scan(reg, str, end, region, ONIG_OPTION_NONE, scan_callback, NULL);
32   if (r >= 0) {
33     fprintf(stdout, "total: %d match\n", r);
34   }
35   else { /* error */
36     char s[ONIG_MAX_ERROR_MESSAGE_LEN];
37     onig_error_code_to_str((OnigUChar* )s, r);
38     fprintf(stderr, "ERROR: %s\n", s);
39     return -1;
40   }
41 
42   onig_region_free(region, 1 /* 1:free self, 0:free contents only */);
43   return 0;
44 }
45 
46 static int
exec(OnigEncoding enc,OnigOptionType options,char * apattern,char * astr)47 exec(OnigEncoding enc, OnigOptionType options, char* apattern, char* astr)
48 {
49   int r;
50   unsigned char *end;
51   regex_t* reg;
52   OnigErrorInfo einfo;
53   UChar* pattern_end;
54   UChar* pattern = (UChar* )apattern;
55   UChar* str     = (UChar* )astr;
56 
57   onig_initialize(&enc, 1);
58 
59   pattern_end = pattern + onigenc_str_bytelen_null(enc, pattern);
60 
61   r = onig_new(&reg, pattern, pattern_end, options, enc, ONIG_SYNTAX_DEFAULT, &einfo);
62   if (r != ONIG_NORMAL) {
63     char s[ONIG_MAX_ERROR_MESSAGE_LEN];
64     onig_error_code_to_str((OnigUChar* )s, r, &einfo);
65     fprintf(stderr, "ERROR: %s\n", s);
66     return -1;
67   }
68 
69   end = str + onigenc_str_bytelen_null(enc, str);
70   r = scan(reg, str, end);
71 
72   onig_free(reg);
73   onig_end();
74   return 0;
75 }
76 
77 
main(int argc,char * argv[])78 extern int main(int argc, char* argv[])
79 {
80   exec(ONIG_ENCODING_UTF8, ONIG_OPTION_NONE,
81        "\\Ga+\\s*", "a aa aaa baaa");
82 
83   fprintf(stdout, "\n");
84   exec(ONIG_ENCODING_UTF8, ONIG_OPTION_NONE,
85        "a+\\s*", "a aa aaa baaa");
86 
87   return 0;
88 }
89