美文网首页
模块(11)re

模块(11)re

作者: Sandra_liu | 来源:发表于2021-07-04 23:29 被阅读0次
    #!/usr/bin/env python
    # coding=utf-8
    
    # encoding: UTF-8
    import re
    
    # • re.compile(pattern[, flags]) 把正则表达式语法转化成正则表达式对象
    
    
    # 将正则表达式编译成Pattern对象
    pattern = re.compile(u'你好')
    
    # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
    match = pattern.match(u'你好,世界!')
    
    print(match)
    
    if match:
        # 使用Match获得分组信息
        print("result:", match.group())
    
    
    
    #!/usr/bin/env python
    # coding=utf-8
    import re
    
    # • re.match(pattern,string[, flags]) 在字符串的开始位置尝试匹配正则表达式
    
    m = re.match('hello', 'hello world!')
    print(m.group())
    
    
    #!/usr/bin/env python
    # coding=utf-8
    
    import re
    
    # re 模块常用方法:
    # • re.compile(pattern[, flags]) 把正则表达式语法转化成正则表达式对象
    
    # 将正则表达式编译成Pattern对象
    pattern = re.compile(r'world')
    
    # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
    # 这个例子中使用match()无法成功匹配
    match = pattern.search('hello world!')
    
    if match:
        # 使用Match获得分组信息
        print(match.group())
    
    
    #!/usr/bin/env python
    # coding=utf-8
    
    
    import re
    
    # • re.compile(pattern[, flags]) 把正则表达式语法转化成正则表达式对象
    # • re.findall() 显示出字符串中模式的所有匹配项。
    
    p = re.compile(r'\d+')
    print(p.split('one1two2three3four4'))
    print(p.findall('one1two2three3four4'))
    
    
    #!/usr/bin/env python
    # coding=utf-8
    
    import re
    
    # • re.search(pattern, string[, flags]) 在整个字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。
    
    text = "Example 3: There is 1 date 10/25/95 in here!"
    m = re.search("(\d{1,2})/(\d{1,2})/(\d{2,4})", text)
    print(m.group())
    
    print(m.group(1), m.group(2), m.group(3))
    month, day, year = m.group(1, 2, 3)
    print(month, day, year)
    
    

    相关文章

      网友评论

          本文标题:模块(11)re

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