1// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s
2//
3// UNSUPPORTED: darwin, target={{.*solaris.*}}
4
5#include <assert.h>
6#include <regex.h>
7#include <stdio.h>
8#include <stdlib.h>
9
10#ifndef __arraycount
11#define __arraycount(a) ((sizeof(a) / sizeof(a[0])))
12#endif
13
14void test_matched(const regex_t *preg, const char *string) {
15 int rv = regexec(preg: preg, String: string, nmatch: 0, NULL, eflags: 0);
16 if (!rv)
17 printf(format: "%s: matched\n", string);
18 else if (rv == REG_NOMATCH)
19 printf(format: "%s: not-matched\n", string);
20 else
21 abort();
22}
23
24void test_print_matches(const regex_t *preg, const char *string) {
25 regmatch_t rm[10];
26 int rv = regexec(preg: preg, String: string, __arraycount(rm), pmatch: rm, eflags: 0);
27 if (!rv) {
28 for (size_t i = 0; i < __arraycount(rm); i++) {
29 // This condition shall be simplified, but verify that the data fields
30 // are accessible.
31 if (rm[i].rm_so == -1 && rm[i].rm_eo == -1)
32 continue;
33 printf(format: "matched[%zu]='%.*s'\n", i, (int)(rm[i].rm_eo - rm[i].rm_so),
34 string + rm[i].rm_so);
35 }
36 } else if (rv == REG_NOMATCH)
37 printf(format: "%s: not-matched\n", string);
38 else
39 abort();
40}
41
42int main(void) {
43 printf(format: "regex\n");
44
45 {
46 regex_t regex;
47 int rv = regcomp(preg: &regex, pattern: "[[:upper:]]\\([[:upper:]]\\)", cflags: 0);
48 assert(!rv);
49
50 test_matched(preg: &regex, string: "abc");
51 test_matched(preg: &regex, string: "ABC");
52
53 test_print_matches(preg: &regex, string: "ABC");
54
55 regfree(preg: &regex);
56 }
57
58 {
59 regex_t regex;
60 int rv = regcomp(preg: &regex, pattern: "[[:upp:]]", cflags: 0);
61 assert(rv);
62
63 char errbuf[1024];
64 regerror(errcode: rv, preg: &regex, errbuf: errbuf, errbuf_size: sizeof errbuf);
65 printf(format: "error: %s\n", errbuf);
66
67 regfree(preg: &regex);
68 }
69
70 // CHECK: regex
71 // CHECK: abc: not-matched
72 // CHECK: ABC: matched
73 // CHECK: matched[0]='AB'
74 // CHECK: matched[1]='B'
75 // CHECK: error:{{.*}}
76
77 return 0;
78}
79

source code of compiler-rt/test/sanitizer_common/TestCases/Posix/regex.cpp