Problem of the Day
A new programming or logic puzzle every Mon-Fri

Simple Regex Parser

That title sounds daunting. Fear not! Our regex parser will be quite simple. We'll be creating a function that tags in pattern and a string to match against. The parser only needs to recognize one special character, *. If the pattern matches against the string return true, else false. Here are some example inputs/outputs:

parse('abc', 'abc')
> true

parse('a*bc', 'abc')
> true

parse('*ca', 'cba')
> false

parse('c*a', 'cccca')
> true

As a quick refresher, the * character matches zero or more occurrences of the preceding character in a row.

Permalink: http://problemotd.com/problem/simple-regex-parser/

Comments:

  • Nick Krichevsky - 10 years, 7 months ago

    Pretty sure I got it, I met all the requirements above, so I think I got it, but ... http://xkcd.com/1171/

    s = "ccccccca"
    p = "*ca"
    
    def stargex(string,pattern):
        if '*' in pattern:
            pattern = pattern.replace('*','')
            if pattern in string:
                return True
            else:
                return False
        else:
            if pattern == string:
                return True
            else:
                return False
    print stargex(s,p)  
    

    reply permalink

  • Pericolo - 10 years, 7 months ago

    I guess your code gives the wrong output for inputs such as: s = "cccab", p = "*ca"

    A simple "if pattern in string" after removing the '*' from the pattern just won't do. It takes more than that.

    reply permalink

  • Nick Krichevsky - 10 years, 7 months ago

    Damn you're right. I'll go rethink this.

    reply permalink

  • Max Burstein - 10 years, 7 months ago

    lol I love that xkcd.

    On another note after checking your code I realize I made a mistake on the last sample output. It originally said *ca for the pattern. However, that has no preceding characters so it's an invalid regex so I changed it to c*a which matches what I was going for there.

    reply permalink

Content curated by @MaxBurstein