Add str_match() to str_util.c

This commit is contained in:
Stefan Rueger
2023-05-22 00:11:37 +01:00
parent 42d14cc195
commit 5ca48353c7
2 changed files with 17 additions and 4 deletions

View File

@@ -1218,6 +1218,7 @@ int str_ends(const char *str, const char *ends);
int str_casestarts(const char *str, const char *starts);
int str_caseends(const char *str, const char *ends);
int str_caseeq(const char *str1, const char *str2);
int str_match(const char *pattern, const char *string);
int str_casematch(const char *pattern, const char *string);
char *str_sprintf(const char *fmt, ...);
char *str_lc(char *s);

View File

@@ -76,7 +76,7 @@ int str_caseends(const char *str, const char *ends) {
/*
* Match string against the partname pattern, returning 1 if it matches, 0 if
* not. Note: str_casematch() is a modified old copy of !fnmatch() from the
* not. Note: str_match_core() is a modified old copy of !fnmatch() from the
* GNU C Library (published under GLP v2), which uses shell wildcards for
* constructing patterns, ie, *, ? and single character classes, eg, [^0-6].
* Used for portability.
@@ -86,7 +86,11 @@ inline static int fold(int c) {
return (c >= 'A' && c <= 'Z')? c+('a'-'A'): c;
}
int str_casematch(const char *pattern, const char *string) {
inline static int nofold(int c) {
return c;
}
static int str_match_core(const char *pattern, const char *string, int (*fold)(int c)) {
unsigned char c;
const char *p = pattern, *n = string;
@@ -118,7 +122,7 @@ int str_casematch(const char *pattern, const char *string) {
unsigned char c1 = fold(c == '\\'? *p : c); // This char
for(--p; *n; ++n) // Recursively check reminder of string for *
if((c == '[' || fold(*n) == c1) && str_casematch(p, n) == 1)
if((c == '[' || fold(*n) == c1) && str_match_core(p, n, fold) == 1)
return 1;
return 0;
}
@@ -196,6 +200,14 @@ int str_casematch(const char *pattern, const char *string) {
return *n == 0;
}
int str_match(const char *pattern, const char *string) {
return str_match_core(pattern, string, nofold);
}
int str_casematch(const char *pattern, const char *string) {
return str_match_core(pattern, string, fold);
}
// Return a malloc'd string with the sprintf() result
char *str_sprintf(const char *fmt, ...) {
@@ -254,7 +266,7 @@ char *str_ucfirst(char *s) {
// Convert unsigned to ASCII string; caller needs to allocate enough space for buf
char *str_utoa(unsigned n, char *buf, int base) {
unsigned q;
char *cp, *cp2;
char *cp;
if(base < 2 || base > 36) {
*buf = 0;