Python 模糊匹配:glob, re

发布时间:2019-08-14 12:44:09编辑:auto阅读(2142)

    '''
    fnmatch模块: 提供对Unix Shell通配符的支持
    Pattern Meaning 
    *       matches everything 
    ?       matches any single character 
    [seq]   matches any character in seq 
    [!seq]  matches any character not in seq 

    '''

    import os
    import fnmatch
    for file in os.listdir('.'):
        if fnmatch.fnmatch(file, '*.py'):
            print file

    '''
    glob模块: 查找所有满足Unix Shell模式规则的路径名
    '''

    import os
    import glob
    for f in glob.glob(os.path.join(os.path.abspath('.'), '*')):
        print f


    Python的正则表达式类似于Perl语言。


    re正则表达式使用'\'进行转义, 而Python语言也使用'\'在字符串的转义;因此,为了匹配'\', 必须使用'\\\\'作为模式。
    因为正则表达式必须是\\,而在字符串中每一个\需要两个\\表示。


    对于正则表达式模式,我们可以使用原始字符串(raw string)。原始字符串中的\只作为普通字符串处理。因此,r'\n'表示两个
    字符,'\'和'n',但是在普通字符串中, '\n'将作为换行符处理。


    re中的特殊字符:
    '.' 匹配任意字符, 除了换行。如果 DOTALL标记打开,将匹配所有字符,包括换行。
    '^' 匹配字符串的开始。
    '$' 匹配字符串的结束。


    '*' 0或多次重复匹配。
    '+' 1或多次重复匹配。
    '?' 0次或1次匹配。
    *?, +?, ?? 对应于'*', '+', '?'的非贪心匹配。
    {m} m次重复匹配
    {m, n} m到n次重复匹配,省略m表示m = 0, 省略n表示n无穷大。
    {m, n}? 与*?, +?, ??类似, 非贪心匹配。
    []  匹配字符集。
    |   A|B,表示匹配A或B。
    ()     正则表达中组的概念。


    \d  匹配十进制数
    \D  匹配非非数字字符
    \s  匹配空白
    \S  匹配非空白
    \w  匹配任意数字和字母
    \W  匹配任意非数字和字母


    url = 'http://www.contoso.com:8080/letters/readme.html'
    obj = re.match(r'(.*)//(.*):(\d+)(.*)', url)
    print obj.groups()
    
    lstStr = ['local 127.0.0.1', 'Lucy 192.168.130.2', 'Link 192.168.130.224']
    for s in lstStr:
        obj = re.match(r'.*?(\d+.\d+.\d+.\d+).*?', s)
        print obj.groups()
    


关键字

上一篇: Python基础学习

下一篇: Python实现简单的API