一说起通配符,大家非常快就会想起*和?

号,有了通配符,使得表达能力大大增强,非常多linux命令都支持这个东西,事实上就是glob style pattern.

就连redis的keys命令都支持glob.



我要实现的glob,支持下面特性:

  • 星号*匹配0个或多个随意字符
  • ?

    匹配确切的一个随意字符

  • [characters]匹配随意一个方括号内的字符,比方[abc],要么匹配a,要么匹配b,要么匹配c.
  • [!character]排除方括号内的字符
  • [character-character],表示2个字符范围内的都能够匹配,如[a-z],[0-9]

实现这个东西事实上挺简单的,从左往右扫描s串和p串,假设最后都走到了结尾,那么就是能够匹配的.

主要难点在于*号的匹配.由于*号能够匹配0个或者多个,所以须要试探回溯.这里通过保存*号位置,假设后面的走不通了,就拉回*号位置,贪婪匹配.

至于方括号的展开,弄个include和exclude变量就非常清晰了.

以下上代码.

#coding=utf-8
def build_expand(p):#方括号展开
ptr2include = {}
ptr2exclude = {}
ptr2next = {}
len_p = len(p)
pPtr = 0
while pPtr<len_p:
if p[pPtr] == '[':
start = pPtr
pPtr += 1
include = set([])
exclude = set([])
while p[pPtr]!=']':
if p[pPtr]=='!':
exclude.add(p[pPtr+1])
pPtr += 2
elif p[pPtr+1] == '-':
include.update({chr(x) for x in range(ord(p[pPtr]),ord(p[pPtr+2])+1)})
pPtr += 3
else:
include.add(p[pPtr])
pPtr += 1
if include:
ptr2include[start] = include
if exclude:
ptr2exclude[start] = exclude
ptr2next[start] = pPtr + 1
else:
pPtr += 1
return ptr2include, ptr2exclude, ptr2next def isMatch(s, p):
len_s = len(s); len_p = len(p)
sPtr = pPtr = ss = 0
star = None
ptr2include, ptr2exclude, ptr2next = build_expand(p)
while sPtr<len_s:
if pPtr<len_p and (p[pPtr] in ['?',s[sPtr]]):
sPtr += 1; pPtr += 1
continue
if pPtr<len_p and p[pPtr] == '[':
if pPtr in ptr2include and s[sPtr] in ptr2include[pPtr]:
sPtr += 1
pPtr = ptr2next[pPtr]
continue
if pPtr in ptr2exclude and s[sPtr] not in ptr2exclude[pPtr]:
sPtr += 1
pPtr = ptr2next[pPtr]
continue
if pPtr<len_p and p[pPtr]=='*':
star = pPtr; pPtr += 1; ss = sPtr
continue
if star is not None:
pPtr = star + 1; ss += 1; sPtr = ss
continue
return False
while pPtr<len(p) and p[pPtr]=='*':
pPtr += 1
return pPtr == len_p if __name__ == '__main__':
params = [
("aa","a"),
("aa","aa"),
("aaa","aa"),
("aa", "*"),
("aa", "a*"),
("ab", "?*"),
("aab", "c*a*b"),
("cab", "c*a*b"),
("cxyzbazba", "c*ba"),
('abc','ab[a-c]'),
('abd','ab[a-c]'),
('abe','ab[cde]'),
('abe','ab[!e]'),
('abe','ab[!c]'),
] for p in params:
print p,isMatch(*p)

执行结果是

('aa', 'a') False

('aa', 'aa') True

('aaa', 'aa') False

('aa', '*') True

('aa', 'a*') True

('ab', '?

*') True

('aab', 'c*a*b') False

('cab', 'c*a*b') True

('cxyzbazba', 'c*ba') True

('abc', 'ab[a-c]') True

('abd', 'ab[a-c]') False

('abe', 'ab[cde]') True

('abe', 'ab[!e]') False

('abe', 'ab[!c]') True

飘逸的python - 实现glob style pattern的更多相关文章

  1. 飘逸的python - 性能调优利器profile及其意义

    VIM 的作者Bram Moolenaar在一篇叫高效文本编辑器的7个习惯的ppt中有这么一段话. Three basic steps 1.    Detect inefficiency 2.    ...

  2. 飘逸的python - __new__、__init__、__call__傻傻分不清

    __new__: 对象的创建,是一个静态方法.第一个參数是cls.(想想也是,不可能是self,对象还没创建,哪来的self) __init__ : 对象的初始化, 是一个实例方法,第一个參数是sel ...

  3. Python:glob

    学习自: (1)Python标准库glob模块_lianghe77的博客-CSDN博客_glob库 (2)Python:glob与os.listdir_鳄鱼的博客-CSDN博客 (3)python文件 ...

  4. python fnmatch & glob

    1,转载:Python模块学习 - fnmatch & glob - Dahlhin - 博客园 (cnblogs.com) 介绍 fnmatch 和 glob 模块都是用来做字符串匹配文件名 ...

  5. python 编程的 Style Guide

    Python 的作者既优雅又高冷又 鬼毛的 再 PEP8 里规定了 Python 程序编写规范.(风格和格式) 一.基本观念 1.可读性之上,代码被读的次数肯定比被写的次数多.因此作者十分重视代码的可 ...

  6. 飘逸的python - 增强的格式化字符串format函数

    自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足.那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱. 语法 它通过{}和 ...

  7. 【leetcode❤python】 290. Word Pattern

    #-*- coding: UTF-8 -*-class Solution(object):    def wordPattern(self, pattern, str):        "& ...

  8. 飘逸的python - 编码杂症之在字符串前面加u

      有时候我们从其它地方接受的字符串经过艰难跋涉,它变了个样.比如收到的是'\u6253\u602a\u8005'而不是u'\u6253\u602a\u8005'. 明明肉眼看起来只需要加个u,但是怎 ...

  9. google python/c++ code style naming

    python: Guidelines derived from Guido's Recommendations Type Public Internal Packages lower_with_und ...

随机推荐

  1. [Swift通天遁地]三、手势与图表-(9)制作五彩缤纷的气泡图表

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  2. [Swift通天遁地]九、拔剑吧-(1)实现在程序中跳转到微信、App Store、地图

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  3. Django day26 HyperlinkedIdentityField,序列化组件的数据校验以及功能的(全局,局部)钩子函数,序列化组件的反序列化和保存

    一:HyperlinkedIdentityField(用的很少):传三个参数:第一个路由名字,用来反向解析,第二个参数是要反向解析的参数值,第三个参数:有名分组的名字 -1 publish = ser ...

  4. 高斯消元_HihoCoderOffer6_03

    题目3 : 图像算子 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 在图像处理的技术中,经常会用到算子与图像进行卷积运算,从而达到平滑图像或是查找边界的效果. 假设原图 ...

  5. springboot自定义常量配置

    现在你建一个类: import org.springframework.boot.context.properties.ConfigurationProperties; /** * Created b ...

  6. js基础---数据类型转换

    js中数据类型: 简单数据类型: number:233,-34,0x23,023 string:"hello"或者'hello' boolean:true.false undefi ...

  7. Python之IPython开发实践

    Python之IPython开发实践 1. IPython有行号. 2. Tab键自动完成,当前命名空间任何与已输入字符串相匹配的变量就会被找出来. 3. 内省机制,在变量前或者后面加上(?)问号,就 ...

  8. Java&Xml教程(五)使用SAX方式解析XML文件

    Java SAX解析机制为我们提供了一系列的API来处理XML文件,SAX解析和DOM解析方式不太一样,它并不是將XML文件内容一次性全部加载,而是连续的部分加载. javax.xml.parsers ...

  9. 2017-5新版ionic3.1 新命令及一些常用命令

    ionic3.1的新命令: # ionic cordova --help //== 查看命令 # ionic cordova resources // 其中 icon.png (1024*1024) ...

  10. html5——css选择器

    复习 div>p: 子代 div+p:div后面相邻的第一个p div~p: div后面所有的兄弟p 属性选择器 标志:[]:区别于id选择器:#,区别于类名选择器:. 特殊符号:^:开头    ...