Wildcard matching in Python

吃可爱长大的小学妹 提交于 2019-12-25 05:17:13

问题


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

So

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

Returns 4

Also

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/41969134/wildcard-matching-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!