added re9_subst() and sample for it
[libre9.git] / src / test1.c
blob2da46887815f25025e73ad3333adaacb1c897462
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
6 #include "libre9/re9.h"
9 int main (int argc, char *argv[]) {
10 re9_sub_t rs[10];
11 re9_prog_t *p;
12 re9_prog_prepared_t *prp;
13 const char *errmsg, *restr;
14 int flg = RE9_FLAG_NONUTF8;
15 /* */
16 if (argc > 1 && strcmp(argv[1], "-d") == 0) {
17 flg |= RE9_FLAG_DUMPPRG;
18 argv[1] = argv[0];
19 ++argv;
20 --argc;
22 /* */
23 if (argc < 3) { fprintf(stderr, "usage: %s regexp string...\n", argv[0]); exit(1); }
24 /* */
25 restr = argv[1];
26 if (restr[0] == '/' && strchr(restr+1, '/')) {
27 for (++restr; *restr != '/'; ++restr) {
28 switch (*restr) {
29 case 'i': flg |= RE9_FLAG_CASEINSENS; break;
30 case 'u': flg &= ~RE9_FLAG_NONUTF8; break;
31 default:
32 fprintf(stderr, "invalid regexp option: '%c'\n", *restr);
33 exit(1);
36 ++restr;
38 p = re9_compile(restr, flg, &errmsg);
39 if (p == NULL) { fprintf(stderr, "FATAL: invalid regexp '%s': %s\n", argv[1], errmsg); exit(2); }
40 if ((prp = re9_prepare(p)) == NULL) { fprintf(stderr, "FATAL: can't prepare regexp!\n"); exit(2); }
41 /* */
42 for (int f = 2; f < argc; ++f) {
43 int res;
44 if (f > 2) printf("===============================\n");
45 printf("(%d) %s VIA %s\n", re9_nsub(p), argv[f], argv[1]);
46 if ((res = re9_prepared_execute(prp, flg, argv[f], rs, 10)) > 0) {
47 for (int c = 0; c < 10; ++c) {
48 if (rs[c].sp != NULL && rs[c].ep != NULL) {
49 printf(" %d:(%d,%d) <", c, rs[c].sp-argv[f], rs[c].ep-argv[f]);
50 fwrite(rs[c].sp, rs[c].ep-rs[c].sp, 1, stdout);
51 fputc('>', stdout);
54 } else if (res < 0) {
55 printf("OUT OF MEMORY!");
57 printf("\n");
59 /* */
60 re9_prepared_free(prp);
61 re9_free(p);
62 /* */
63 return 0;