python通配符,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

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值