How do I write a simple regular expression pattern matching function in C or C++?

后端 未结 9 1124
我寻月下人不归
我寻月下人不归 2021-02-01 06:58

This is a question in my paper test today, the function signature is

int is_match(char* pattern,char* string)

The pattern is limited to only A

9条回答
  •  情书的邮戳
    2021-02-01 07:51

    Simple recursive implementation. It's slow but easy to understand:

    int is_match(char *pattern, char *string)
    {
        if (!pattern[0]) {
            return !string[0];
        } else if (pattern[1] == '?') {
            return (pattern[0] == string[0] && is_match(pattern+2, string+1))
                || is_match(pattern+2, string);
        } else if (pattern[1] == '*') {
            size_t i;
            for (i=0; string[i] == pattern[0]; i++)
                if (is_match(pattern+2, string+i)) return 1;
            return 0;
        } else {
            return pattern[0] == string[0] && is_match(pattern+1, string+1);
        }
    }
    

    Hope I got it all right.

提交回复
热议问题