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

后端 未结 9 938
我寻月下人不归
我寻月下人不归 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:47

    Didn't test this, actually code it, or debug it, but this might get you a start...

    for each character in the pattern
      if pattern character after the current one is *
        // enter * state
        while current character from target == current pattern char, and not at end
          get next character from target
        skip a char from the pattern
      else if pattern character after the current one is ?
        // enter ? state
        if current character from target == current pattern char
          get next char from target
        skip a char from the pattern
      else
        // enter character state
        if current character from target == current pattern character
          get next character from target
        else
          return false
    return true
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 07:52

    See This Question for a solution you can not submit. See this paper for a description of how to implement a more readable one.

    0 讨论(0)
提交回复
热议问题