• re模块


    re模块

    1、什么是正则
      正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过re模块实现。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。

    元字符   匹配内容
    w     匹配字母(包含中文)或数字或下划线
    W    匹配非字母(包含中文)或数字或下划线
    s     匹配任意的空白符
    S     匹配任意非空白符
    d     匹配数字
    D     匹配非数字
    A     从字符串开头匹配
         匹配字符串的结束
        匹配一个换行符
         匹配一个制表符
    ^      匹配字符串的开始
    $      匹配字符串的结尾
    .       匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
    [...]      匹配字符组中的字符
    [^...]       匹配除了字符组中的字符的所有字符
    *       匹配0个或者多个左边的字符。
    +         匹配一个或者多个左边的字符。
    ?        匹配0个或者1个左边的字符,非贪婪方式。
    {n}       精准匹配n个前面的表达式。
    {n,m}     匹配n到m次由前面的正则表达式定义的片段,贪婪方式
    a|b      匹配a或者b。
    ()         匹配括号内的表达式,也表示一个组

    2、匹配模式举例
    之前学过的字符串的常用操作:一对一匹配

    s1 = 'abcdefg你好'
    print(s1.find('你好'))
    # 7 返回的是字符串开始的下标

    2.1、单个匹配:

    import re
    1)、w 和 W 汉字字母数字下划线
    print(re.findall('w', '你好Tom123!@#$%^&*()-_=+'))
    # ['你', '好', 'T', 'o', 'm', '1', '2', '3', '_']
    print(re.findall('W', '你好Tom123!@#$%^&*()-_=+'))
    # ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '+']
    
    2)、 s 和 S  空格、TAB、换行符、回车
    print(re.findall('s','a 1	
    
    '))
    # [' ', '	', '
    ', '
    ']
    print(re.findall('S','a 1	
    
    '))
    # ['a', '1']
    
    3)、d 和 D 数字
    print(re.findall('d','你好Tom123!@#$%^&*()-_=+'))
    # ['1', '2', '3']
    print(re.findall('D','你好Tom123!@#$%^&*()-_=+'))
    # ['你', '好', 'T', 'o', 'm', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+']
    
    4)、A 和 ^ 以什么开头,字符串写在后面
    print(re.findall('Ahel','hello123!@#'))
    # ['hel']
    print(re.findall('^hello','hello123!@#'))
    # ['hello']
    
    5)、 和 $ 以什么结尾,字符串写在前面
    print(re.findall('@#','hello123!@#'))
    # ['@#']
    print(re.findall('!@#$','hello123!@#'))
    # ['!@#']
    
    6)、
     和 	 
    print(re.findall('
    ','h e l 
     	 
     123'))
    # ['
    ']
    print(re.findall('	','h e l 
     	 
     123'))
    # ['	']
    print(re.findall('
    ','h e l 
     	 
     123'))
    # ['
    ']

    2.2、重复匹配 . ? * + {m,n} .* .*?

    import re
    # . 匹配任意字符,除了换行符(re.DOTALL这个参数可以匹配
    )
    print(re.findall('a.b','aab a b a1b a*b a.b a
    b'))
    # ['aab', 'a b', 'a1b', 'a*b', 'a.b']
    print(re.findall('a.b','aab a b a1b a*b a.b a
    b',re.DOTALL))
    # ['aab', 'a b', 'a1b', 'a*b', 'a.b', 'a
    b']
    
    # ? 匹配0个或1个左边字符
    print(re.findall('a?b','aab aaab abb aabb'))
    # ['ab', 'ab', 'ab', 'b', 'ab', 'b']
    
    # * 匹配0个或多个左边字符,满足贪婪匹配
    print(re.findall('a*b','aab aaab abb aabb'))
    # ['aab', 'aaab', 'ab', 'b', 'aab', 'b']
    
    # + 匹配1个或多个左边字符,满足贪婪匹配
    print(re.findall('a+b','ab aab aaab abbb'))
    # ['ab', 'aab', 'aaab', 'ab']
    
    # {m,n}  匹配m个至n个左边字符,满足贪婪匹配
    print(re.findall('a{2,4}b','ab aab aaab aaaab aaaaab'))
    # ['aab', 'aaab', 'aaaab', 'aaaab']
    
    # .* 匹配0个或多个任意非换行字符,贪婪匹配(从头到尾匹配出来),加re.DOTALL就可以匹配换行符
    print(re.findall('a.*b','ab aab a*()b a b a
    b'))
    # ['ab aab a*()b a b']
    print(re.findall('a.*b','ab aab a*()b a b a
    b',re.DOTALL))
    # ['ab aab a*()b a b a
    b']
    
    
    # .*? 匹配0个或多个任意非换行字符,非贪婪匹配(一个一个匹配出来),加re.DOTALL就可以匹配换行符
    #这里的?不是0个或1个的意思,而是表示.*模式的非贪婪匹配,re.DOTALL可以匹配换行
    print(re.findall('a.*?b','ab aab a*()b aaaab a b a
    b'))
    # ['ab', 'aab', 'a*()b', 'aaaab', 'a b']
    
    # []: 括号中可以放任意一个字符,一个中括号代表一个字符
    # - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间,只能放在两边
    # ^ 在[]中表示取反的意思.
    
    print(re.findall('a.b', 'a1b a3b aeb a*b arb a_b'))  # ['a1b', 'a3b', 'a4b', 'a*b', 'arb', 'a_b']
    print(re.findall('a[abc]b', 'aab abb acb adb afb a_b'))  # ['aab', 'abb', 'acb']
    print(re.findall('a[0-9]b', 'a1b a3b aeb a*b arb a_b'))  # ['a1b', 'a3b']
    print(re.findall('a[a-z]b', 'a1b a3b aeb a*b arb a_b'))  # ['aeb', 'arb']
    print(re.findall('a[a-zA-Z]b', 'aAb aWb aeb a*b arb a_b'))  # ['aAb', 'aWb', 'aeb', 'arb']
    print(re.findall('a[0-9][0-9]b', 'a11b a12b a34b a*b arb a_b'))  # ['a11b', 'a12b', 'a34b']
    print(re.findall('a[*-+]b','a-b a*b a+b a/b a6b'))  # ['a*b', 'a+b']
    
    # - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间.
    print(re.findall('a[-*+]b','a-b a*b a+b a/b a6b'))  # ['a-b', 'a*b', 'a+b']
    print(re.findall('a[^a-z]b', 'acb adb a3b a*b'))  # ['a3b', 'a*b']

    2.3、分组:

    () 制定一个规则,将满足规则的结果匹配出来
    找到字符串中'Tom_123 Mike_123 Jack_123'的 Tom、Mike、Jack
    print(re.findall('([a-zA-Z]+)_123','Tom_123 Mike_123 Jack_123'))
    
    找出a标签中的URL
    print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
    
    | 或匹配 
    print(re.findall('Tom|Mike|Jack', ' Tom123MikeaabJack'))  # ['alex', '太白', 'wusir', '太白']
    print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))  # ['ies', 'y']
    print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))  # ['companies', 'company']
    分组() 中加入?: 表示将整体匹配出来而不只是()里面的内容。

    3、常用方法举例

    3.1、findall 全部找到返回一个列表。
    print(re.findall('a', 'alexwusirbarryeval'))  # ['a', 'a', 'a']
    
    3.2、search 只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
    print(re.search('Tom|Mike', 'Mike and Tom are 18 years old'))  # <_sre.SRE_Match object; span=(0, 4), match='Mike'>
    print(re.search('Tom|Mike', 'Mike and Tom are 18 years old').group())  # Mike
    
    3.3、match 同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
    print(re.match('Tom|Mike', 'Mike and Tom are 18 years old')) # <_sre.SRE_Match object; span=(0, 4), match='Mike'>
    print(re.match('Tom|Mike', 'Mike and Tom are 18 years old').group()) # Mike
    
    如果开头没有找到,则返回None
    print(re.match('Tom|Mike', '123 Mike and Tom are 18 years old')) #None
    这时如果group()就会报错
    
    3.4、split 分割 可按照任意分割符进行分割
    print(re.split('[ ::,;;,]','Tom:Mike:Jack,Rose;Bob;Lucy'))  #['Tom', 'Mike', 'Jack', 'Rose', 'Bob', 'Lucy']
    
    3.5、sub 替换
    print(re.sub('Tom', 'Mike', 'Tom is a student, Tom is 18 years old。')) # Mike is a student, Mike is 18 years old。
    
    可以指定替换的次数
    print(re.sub('Tom', 'Mike', 'Tom is a student, Tom is 18 years old。',1)) #Mike is a student, Tom is 18 years old。
    
    也可以使用位置替换,将所有的字符串按位置编号重新组合
    print(re.sub('([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)', r'523416789', r'Tom and Mike are friends'))
    # Mike and Tom are friends
    print(re.sub('([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)', r'52341', r'Tom and Mike are friends'))
    # Mike and Tom
    
    3.6、compile表达式
    obj=re.compile('d{2}')
    print(obj.search('abc123eeee').group()) #12
    print(obj.findall('abc123eeee')) #['12'],重用了obj
    
    3.7、finditer 迭代器
    ret = re.finditer('d', 'ds3sy4784a')   #finditer返回一个存放匹配结果的迭代器
    print(ret)  # <callable_iterator object at 0x10195f940>
    print(next(ret).group())  #查看第一个结果
    print(next(ret).group())  #查看第二个结果
    print([i.group() for i in ret])  #查看剩余的结果

    4、命名分组举例(了解)

    命名分组匹配:
    ret = re.search("<(?P<tag_name>w+)>w+</(?P=tag_name)>","<h1>hello</h1>")
    还可以在分组中利用?<name>的形式给分组起名字
    获取的匹配结果可以直接用group('名字')拿到对应的值
    print(ret.group('tag_name'))  #结果 :h1
    print(ret.group())  #结果 :<h1>hello</h1>
    
    ret = relx.search(r"<(w+)>w+</1>","<h1>hello</h1>")
    如果不给组起名字,也可以用序号来找到对应的组,表示要找的内容和前面的组内容一致
    获取的匹配结果可以直接用group(序号)拿到对应的值
    print(ret.group(1))
    print(ret.group())  #结果 :<h1>hello</h1>
    View Code

    5、相关小练习

    1、1-2*(60+(-40.35/5)-(-4*3))"
      1.1 匹配所有的整数
    print(re.findall('d+',"1-2*(60+(-40.35/5)-(-4*3))"))
    # ['1', '2', '60', '40', '35', '5', '4', '3']
    
      1.2 匹配所有的数字(包含小数)
    print(re.findall(r'd+.?d*|d*.?d+', "1-2*(60+(-40.35/5)-(-4*3))"))
    # ['1', '2', '60', '40.35', '5', '4', '3']
    
      1.3 匹配所有的数字(包含小数包含负号)
    print(re.findall(r'-?d+.?d*|d*.?d+', "1-2*(60+(-40.35/5)-(-4*3))"))
    ['1', '-2', '60', '-40.35', '5', '-4', '3']
    
    
    2、匹配一段你文本中的每行的邮箱
    http://blog.csdn.net/make164492212/article/details/51656638 匹配所有邮箱
    实例1、只允许英文字母、数字、下划线、英文句号、以及中划线组成
    举例:zhangsan-001@gmail.com 
    
    分析邮件名称部分:
    26个大小写英文字母表示为a-zA-Z
    数字表示为0-9
    下划线表示为_
    中划线表示为-
    由于名称是由若干个字母、数字、下划线和中划线组成,所以需要用到+表示多次出现
    根据以上条件得出邮件名称表达式:[a-zA-Z0-9_-]+ 
    
    分析域名部分:
    一般域名的规律为“[N级域名][三级域名.]二级域名.顶级域名”,比如“qq.com”、“www.qq.com”、“mp.weixin.qq.com”、“12-34.com.cn”,分析可得域名类似“** .** .** .**”组成。
    “**”部分可以表示为[a-zA-Z0-9_-]+
    “.**”部分可以表示为.[a-zA-Z0-9_-]+
    多个“.**”可以表示为(.[a-zA-Z0-9_-]+)+
    综上所述,域名部分可以表示为[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+
    
    最终表达式: 
    由于邮箱的基本格式为“名称@域名”,需要使用“^”匹配邮箱的开始部分,用“$”匹配邮箱结束部分以保证邮箱前后不能有其他字符,所以最终邮箱的正则表达式为: 
    ^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$
    
    实例2、名称允许汉字、字母、数字,域名只允许英文域名
    举例:杨元庆001Abc@lenovo.com.cn
    
    分析邮件名称部分:
    汉字在正则表示为[u4e00-u9fa5]
    字母和数字表示为A-Za-z0-9 
    通过分析得出邮件名称部分表达式为[A-Za-z0-9u4e00-u9fa5]+
        
    分析邮件域名部分
    邮件部分可以参考实例1中的分析域名部分。 
    得出域名部分的表达式为[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+。
    
    最终表达式: 
    我们用@符号将邮箱的名称和域名拼接起来,因此完整的邮箱表达式为 
    ^[A-Za-z0-9u4e00-u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$
        
    3、匹配一段你文本中的每行的时间字符串 这样的形式:'1995-04-27'
    s1 = '''
    时间就是1980-01-02,2008-03-04
    1980-01-02 is Tom's birthday
    Jack 1931-05-10:2010-10-20
    2018-12-03
    '''
    print(re.findall('d{4}-d{2}-d{2}', s1))
    # ['1980-01-02', '2008-03-04', '1980-01-02', '1931-05-10', '2010-10-20', '2018-12-03']
    
    4、匹配 一个浮点数
    print(re.findall('d+.d*','1.17'))
    # ['1.17']
    
    5、匹配qq号:腾讯从10000开始:
    print(re.findall('[1-9][0-9]{4,}', '2413545136'))
    # ['2413545136']
    
    6、匹配标签
    s1 = '''
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7459977.html" target="_blank">python基础一</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7562422.html" target="_blank">python基础二</a></p>
    <p><a style="text-decoration: underline;" href="https://www.cnblogs.com/jin-xin/articles/9439483.html" target="_blank">Python最详细,最深入的代码块小数据池剖析</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7738630.html" target="_blank">python集合,深浅copy</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8183203.html" target="_blank">python文件操作</a></p>
    <h4 style="background-color: #f08080;">python函数部分</h4>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8241942.html" target="_blank">python函数初识</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8259929.html" target="_blank">python函数进阶</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8305011.html" target="_blank">python装饰器</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8423526.html" target="_blank">python迭代器,生成器</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8423937.html" target="_blank">python内置函数,匿名函数</a></p>
    <p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8743408.html" target="_blank">python递归函数</a></p>
    <p><a style="text-decoration: underline;" href="https://www.cnblogs.com/jin-xin/articles/8743595.html" target="_blank">python二分查找算法</a></p>
    
    '''
    6.1、找到所有的p标签
    ret = re.findall('<p>.*?</p>', s1)
    print(ret)
    
    6.2、找到所有a标签对应的url
    print(re.findall('<a.*?href="(.*?)".*?</a>',s1))
    print(re.findall('href="(.*?)"', s1))
    View Code
  • 相关阅读:
    Android监听器无法跳转的可能原因之一。。。
    627,一个神圣的日子
    Android BottomNavigationView的用法
    Android VideoView未解决,动态读取权限、BottomNavigationView的用法
    Android RecyclerView的补充。
    Android 的Glide、TabLayout、RecyclerView(下一章补充)。
    Android 自定义组件,自定义LinearLayout,ListView等样式的组件
    Android html5和Android之间的交互
    Android WebView的使用
    Android Json转换类对象,并使用
  • 原文地址:https://www.cnblogs.com/dxnui119/p/10057859.html
Copyright © 2020-2023  润新知