core: add match-str and matches? to regex

This commit is contained in:
hellerve 2018-02-27 20:27:44 +01:00
parent 93171ccbaa
commit 3deb6f0658
3 changed files with 50 additions and 0 deletions

View File

@ -100,8 +100,10 @@
(register find (Fn [&String &String] Int))
(register match (Fn [&String &String] (Array String)))
(register match-str (Fn [&String &String] String))
(register global-match (Fn [&String &String] (Array (Array String))))
(register substitute (Fn [&String &String &String Int] String))
(defn matches? [s pat] (/= (find s pat) -1))
)
(defmodule StringCopy

View File

@ -445,6 +445,34 @@ Array String_match(string* s, string* p) {
return a;
}
string String_match_MINUS_str(string* s, string* p) {
string str = *s;
string pat = *p;
int lstr = strlen(str);
int lpat = strlen(pat);
MatchState ms;
string s1 = str;
int anchor = (*pat == '^');
if (anchor) {
pat++; lpat--; /* skip anchor character */
}
prepstate(&ms, str, lstr, pat, lpat);
do {
string res;
reprepstate(&ms);
if ((res=match(&ms, s1, pat))) {
int start = (s1 - str) + 1;
int end = res - str + 1;
int len = end - start;
res = malloc(len + 1);
memcpy(res, str, len);
res[len] = '\0';
return res;
}
} while (s1++ < ms.src_end && !anchor);
return String_empty();
}
/* state for 'gmatch' */
typedef struct GMatchState {
string src; /* current position */

View File

@ -110,11 +110,31 @@
&(match " " "(\\d)")
"match works as expected if not found"
)
(assert-equal test
true
(matches? "banana" "ana")
"matches? works as exptected"
)
(assert-equal test
true
(matches? "banana" "ano")
"matches? works as exptected II"
)
(assert-equal test
&[@"3" @"4"]
(Array.nth &(global-match "1-2 2-3 3-4 4-5" "(\\d)-(\\d)") 2)
"global-match works as expected"
)
(assert-equal test
"1-2"
&(match-str "1-2 2-3 3-4 4-5" "(\\d)-(\\d)")
"match-str works as expected"
)
(assert-equal test
""
&(match-str "1-2 2-3 3-4 4-5" "erik")
"match-str works as expected II"
)
(assert-equal test
"sub 2-3 3-4"
&(substitute "1-2 2-3 3-4" "(\\d)-(\\d)" "sub" 1)