File: regex.cc

package info (click to toggle)
llvm-toolchain-9 1%3A9.0.1-16
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 882,436 kB
  • sloc: cpp: 4,167,636; ansic: 714,256; asm: 457,610; python: 155,927; objc: 65,094; sh: 42,856; lisp: 26,908; perl: 7,786; pascal: 7,722; makefile: 6,881; ml: 5,581; awk: 3,648; cs: 2,027; xml: 888; javascript: 381; ruby: 156
file content (71 lines) | stat: -rw-r--r-- 1,685 bytes parent folder | download | duplicates (9)
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
// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s
//
// UNSUPPORTED: darwin, solaris

#include <assert.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>

#ifndef __arraycount
#define __arraycount(a) ((sizeof(a) / sizeof(a[0])))
#endif

void test_matched(const regex_t *preg, const char *string) {
  int rv = regexec(preg, string, 0, NULL, 0);
  if (!rv)
    printf("%s: matched\n", string);
  else if (rv == REG_NOMATCH)
    printf("%s: not-matched\n", string);
  else
    abort();
}

void test_print_matches(const regex_t *preg, const char *string) {
  regmatch_t rm[10];
  int rv = regexec(preg, string, __arraycount(rm), rm, 0);
  if (!rv) {
    for (size_t i = 0; i < __arraycount(rm); i++) {
      // This condition shall be simplified, but verify that the data fields
      // are accessible.
      if (rm[i].rm_so == -1 && rm[i].rm_eo == -1)
        continue;
      printf("matched[%zu]='%.*s'\n", i, (int)(rm[i].rm_eo - rm[i].rm_so),
             string + rm[i].rm_so);
    }
  } else if (rv == REG_NOMATCH)
    printf("%s: not-matched\n", string);
  else
    abort();
}

int main(void) {
  printf("regex\n");

  regex_t regex;
  int rv = regcomp(&regex, "[[:upper:]]\\([[:upper:]]\\)", 0);
  assert(!rv);

  test_matched(&regex, "abc");
  test_matched(&regex, "ABC");

  test_print_matches(&regex, "ABC");

  regfree(&regex);

  rv = regcomp(&regex, "[[:upp:]]", 0);
  assert(rv);

  char errbuf[1024];
  regerror(rv, &regex, errbuf, sizeof errbuf);
  printf("error: %s\n", errbuf);

  // CHECK: regex
  // CHECK: abc: not-matched
  // CHECK: ABC: matched
  // CHECK: matched[0]='AB'
  // CHECK: matched[1]='B'
  // CHECK: error:{{.*}}

  return 0;
}