aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAlejandro Colomar <colomar.6.4.3@gmail.com>2020-10-17 15:27:49 +0200
committerMichael Kerrisk <mtk.manpages@gmail.com>2020-10-17 16:35:36 +0200
commit7e35a028664bbdd9e2a9a781d46f29e47a3bef8f (patch)
tree194e674df310cadc49a84c54adb8f3ddbf71d995
parent740656b8553408238269770629afd5504fdde17e (diff)
downloadman-pages-7e35a028664bbdd9e2a9a781d46f29e47a3bef8f.tar.gz
regex.3: Add example program
$ gcc -Wall -Wextra -Werror -pedantic regex.c -o regex $ ./regex.3 String = "1) John Driverhacker; 2) John Doe; 3) John Foo; " Matches: #0: offset = 25; length = 7 substring = "John Do" #1: offset = 38; length = 8 substring = "John Foo" Signed-off-by: Alejandro Colomar <colomar.6.4.3@gmail.com> Signed-off-by: Michael Kerrisk <mtk.manpages@gmail.com>
-rw-r--r--man3/regex.342
1 files changed, 42 insertions, 0 deletions
diff --git a/man3/regex.3 b/man3/regex.3
index 7c51329950..3144c2ceb1 100644
--- a/man3/regex.3
+++ b/man3/regex.3
@@ -337,6 +337,48 @@ T} Thread safety MT-Safe
.TE
.SH CONFORMING TO
POSIX.1-2001, POSIX.1-2008.
+.SH EXAMPLES
+.EX
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <regex.h>
+
+#define ARRAY_SIZE(arr) (sizeof((arr)) / sizeof((arr)[0]))
+
+static const char *const str =
+ "1) John Driverhacker;\en2) John Doe;\en3) John Foo;\en";
+static const char *const re = "John.*o";
+
+int main(void)
+{
+ static const char *s = str;
+ regex_t regex;
+ regmatch_t pmatch[1];
+ regoff_t off, len;
+
+ if (regcomp(&regex, re, REG_NEWLINE))
+ exit(EXIT_FAILURE);
+
+ printf("String = \e"%s\e"\en", str);
+ printf("Matches:\en");
+
+ for (int i = 0; ; i++) {
+ if (regexec(&regex, s, ARRAY_SIZE(pmatch), pmatch, 0))
+ break;
+
+ off = pmatch[0].rm_so + (s \- str);
+ len = pmatch[0].rm_eo \- pmatch[0].rm_so;
+ printf("#%d:\en", i);
+ printf("offset = %jd; length = %jd\en", (intmax_t) off, (intmax_t) len);
+ printf("substring = \e"%.*s\e"\en", len, s + pmatch[0].rm_so);
+
+ s += pmatch[0].rm_eo;
+ }
+
+ exit(EXIT_SUCCESS);
+}
+.EE
.SH SEE ALSO
.BR grep (1),
.BR regex (7)