re正则表格式

作者: 阿发贝塔伽马 | 来源:发表于2017-08-02 14:06 被阅读7次
    # coding=utf-8
    # "正则表达式学习"
    import re
    
    # "match方法的工作方式是只有当被搜索字符串的开头匹配模式的时候它才能找到匹配对象"
    match = re.match(r'dog', 'dogsdf cat dog')
    print match.group()
    
    # "开头没有匹配cat,将返回None"
    match = re.match(r'cat', 'dog cat dog')
    print match
    
    # "使用re.search查找匹配任意位置,search方法不会限制只从字符串开头匹配,因此可以在中间查找cat"
    
    search = re.search(r'cat', 'dog catsd dog')
    print search.group(0)
    # "search查找到一个匹配后不会继续查找"
    search = re.search(r'dog', 'dog catsd dog')
    print search.group(0)
    
    # "使用re.findall-所以匹配对象"
    findall = re.findall(r'dog', 'dogsdfs catsd dog')
    print findall
    
    # "使用match.start和match.end方法"
    
    match = re.match(r'dog', 'dogsdf cat dog')
    print match.start(), match.end()
    
    # "使用match.group通过数字分组"
    contactInfo = 'Doe, John: 555-1212'
    
    search = re.search(r'\w+, \w+: \S+', contactInfo)
    print search.start(), search.end()
    print search.group(0)
    search = re.search(r'(\w+), (\w+): (\S+)', contactInfo)
    print search.start(), search.end()
    print search.group(1)
    print search.group(2)
    print search.group(3)
    
    # "通过别名访问分组内容"
    search = re.search(r'(?P<last>\w+), (?P<first>\w+): (?P<phone>\S+)', contactInfo)
    print search.group('last')
    print search.group('first')
    print search.group('phone')
    
    findall = re.findall(r'(\w+), (\w+): (\S+)', contactInfo)
    print findall
    
    html = 'Hello <a href="http://pypix.com" title="pypix">Pypix</a>'\
            'Hello <a href="http://example.com" title"example">Example</a>'
    
    # .*是贪婪模式,将尽可能匹配多的字符
    findall = re.findall(r'(<a.*</a>)', html)
    print findall
    # .*?是非贪婪模式
    findall = re.findall(r'(<a.*?</a>)', html)
    print findall
    
    # "前向定界符和后向定界符"
    strings = ["hello foo", "hello foobar"]
    for string in strings:
        # (?=bar)表示匹配bar
        pattern = re.search(r'foo(?=bar)', string)
        if pattern:
            print 'True'
            print pattern.group()
        else:
            print 'False'
    strings = ["1hello foo", "2hello foobar", "3hello foobaz"]
    
    for string in strings:
        # (?!bar)表示不匹配bar,如"3hello foobaz"
        pattern = re.search(r'foo(?!bar)', string)
        if pattern:
            print 'True'
            print pattern.group()
        else:
            print 'False'
    # "后向界定符类似,但是它查看当前匹配的前面的模式。你可以使用 (?> 来表示肯定界定,(?<! 表示否定界定。"
    
    print '***********************************************'
    strings = [  "hello1 bar",         # returns True
                 "hello2 foobar",      # returns False
                 "hello3 bazbar"]      # returns True
    for string in strings:
        pattern = re.search(r'(?=foo)bar', string)
        if pattern:
            pattern.group()
        else:
            print 'False'
    
    # 条件(IF-Then-Else)模式 (?(?=regex)then|else)
    print '*******************************************'
    strings = [  "<pypix>",    # returns true
                 "<foo",       # returns false
                 "bar>",       # returns false
                 "hello" ]     # returns true
     
    for string in strings:
        # ^表示从开始地方匹配,$匹配到结尾, (<)?表示<出现一次或不出现, 
        # 1表示分组(<),当然也可以为空因为后面跟着一个问号。当且仅当条件成立时它才匹配关闭的尖括号
        pattern = re.search(r'^(<)?[a-z]+(?(1)>)$', string)
        if pattern:
            print 'True'
        else:
            print 'False'
    
    # 无捕获组
    print '*****************************************'
    string = 'hello foobar'
    pattern = re.search(r'(f.*)(b.*)', string)
    print pattern.group()
    print pattern.group(1)
    print pattern.group(2)
    pattern = re.search(r'(h.*)(f.*)(b.*)', string)
    print pattern.group()
    print pattern.group(1)
    print pattern.group(2)
    print pattern.group(3)
    
    pattern = re.search(r'(?:h.*)(f.*)(b.*)', string)
    print pattern.group()
    print pattern.group(1)
    print pattern.group(2)
    
    print '*****************************************'
    pattern = re.search(r'(h.*)(?P<fstar>f.*)(?P<bstar>b.*)', string)
    print pattern.group('fstar')
    print pattern.group('bstar')
    
    # 使用回调函数
    template = "Hello [first_name] [last_name], \
    Thank you for purchasing [product_name] from [store_name]. \
    The total cost of your purchase was [product_price] plus [ship_price] for shipping. \
    You can expect your product to arrive in [ship_days_min] to [ship_days_max] business days. \
    Sincerely, \
    [store_manager_name]"          
    # assume dic has all the replacement data          
    # such as dic['first_name'] dic['product_price'] etc...          
    dic = {          
     "first_name" : "John",          
     "last_name" : "Doe",          
     "product_name" : "iphone",          
     "store_name" : "Walkers",          
     "product_price": "$500",          
     "ship_price": "$10",          
     "ship_days_min": "1",          
     "ship_days_max": "5",          
     "store_manager_name": "DoeJohn"          
    }          
    result = re.compile(r'(.*)')          
    print result.sub('John', template, count=1)
    
    print '*************************************'
    
    # assume dic has all the replacement data          
    # such as dic['first_name'] dic['product_price'] etc...          
    def multiple_replace(dic, text):
        mapRe = map(lambda key : re.escape("["+key+"]"), dic.keys())
        print mapRe
        pattern = "|".join(mapRe)
        return re.sub(pattern, lambda m: dic[m.group()[1:-1]], text)     
    print multiple_replace(dic, template)
    
    
    for key in dic.keys():
        pattern = re.escape("["+key+"]")
        print pattern
    print '***************************'
    inputStr = "hello crifan, nihao crifan";
    replacedStr = re.sub(r"hello (?P<name>\w+), nihao (?P=name)", "\g<name>", inputStr);
    print "replacedStr=",replacedStr; #crifan
    
    print '***************************'
    inputStr = "hello crifan, nihao crifan";
    replacedStr = re.sub(r'crifan', "crifanli", inputStr);
    print "replacedStr=",replacedStr; #crifanli
    
    def pythonReSubDemo():
        """
            demo Pyton re.sub
        """
        inputStr = "hello 123 world 456";
         
        def _add111(matched):
            intStr = matched.group("number"); #123
            intValue = int(intStr);
            addedValue = intValue + 111; #234
            addedValueStr = str(addedValue);
            return addedValueStr;
             
        replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
        print "replacedStr=",replacedStr; #hello 234 world 567
    pythonReSubDemo()
    
    inputStr = "hello 123 world 456";
    search = re.findall('(?P<number>\d+)', inputStr)
    print search
    

    替换

    # 会将匹配
    test = re.sub(ur'[电「『]', ur'”', ur'「闪电分手的『史蒂芬森')
    print test
    

    相关文章

      网友评论

        本文标题:re正则表格式

        本文链接:https://www.haomeiwen.com/subject/bynelxtx.html