]> gitweb.ps.run Git - onefile/commitdiff
add regex.c
authorpatrick-scho <patrick.schoenberger@posteo.de>
Fri, 23 May 2025 11:40:28 +0000 (13:40 +0200)
committerpatrick-scho <patrick.schoenberger@posteo.de>
Fri, 23 May 2025 14:08:34 +0000 (16:08 +0200)
regex.c [new file with mode: 0644]

diff --git a/regex.c b/regex.c
new file mode 100644 (file)
index 0000000..ca7a8f2
--- /dev/null
+++ b/regex.c
@@ -0,0 +1,49 @@
+int match(char r, char t)
+{
+    return r == '.' || r == t;
+}
+int matchstr(const char *r, const char *t)
+{
+    int state = 0, i = (r[0] == '^' ? 1 : 0), j = 0;
+    while (1)
+    {
+        if (r[i] == '\0')
+            return 1;
+        if (r[i] == '$' && r[i + 1] == '\0')
+            return t[j] == '\0';
+        if (t[j] == '\0')
+            return 0;
+
+        if (state == 0) // base case
+        {
+            if (r[i + 1] == '*')
+                state = 1;
+            else if (match(r[i], t[j]))
+                i++, j++;
+            else if (r[0] == '^')
+                return 0;
+            else
+                i = 0;
+        }
+        if (state == 1) // star
+        {
+            if (!match(r[i], t[j]) || match(r[i + 2], t[j]))
+                state = 0, i += 2;
+            else
+                j++;
+        }
+    }
+    return 0;
+}
+
+#include <stdio.h>
+
+int main(int argc, char **argv)
+{
+    if (argc != 3)
+    {
+        printf("Usage: %s <regex> <text>\n", argv[0]);
+        return 2;
+    }
+    return !matchstr(argv[1], argv[2]);
+}