mirror of
https://github.com/carp-lang/Carp.git
synced 2024-09-11 05:25:28 +03:00
core: add match-str and matches? to regex
This commit is contained in:
parent
93171ccbaa
commit
3deb6f0658
@ -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
|
||||
|
@ -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 */
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user