Wildcard matching in Python

I have a class called Pattern, and within it two methods, equates and setwildcard. Equates returns the index in which a substring first appears in a string, and setwildcard sets a wild card character in a substring


p = Pattern('xyz')
t = 'xxxxxyz'

Returns 4


p = Pattern('x*z', '*')
t = 'xxxxxgzx'

Returns 4, because * is the wildcard and can match any letter within t, as long as x and z match. What’s the best way to implement this?


It looks like you’re essentially implementing a subset of regular expressions. Luckily, Python has a library for that built-in! If you’re not familiar with how regular expressions (or, as their friends call them, regexes) work, I highly recommend you read through the documentation for them.

In any event, the function re.search is, I think, exactly what you’re looking for. It takes, as its first argument, a pattern to match, and, as its second argument, the string to match it in. If the pattern is matched, search returns an SRE_Match object, which, conveniently, has a #start() method that returns the index at which the match starts.

To use the data from your example:

 import re
 start_index = re.search(r'x.z', 'xxxxxgzg').start()

Note that, in regexes, . – not * — is the wildcard, so you’ll have to replace them in the pattern you’re using.