• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

正则表达式和re库的知识-python爬虫和信息提取1-北京理工大学-嵩天老师

武飞扬头像
Keep-CodingのToby
帮助1

一、正则表达式

1、基本概念

学新通

         两个字说,正则表达式的特点就是【简洁】。

2、正则表达式常用操作符

学新通

学新通

3、语法实例

学新通

  在此解释最后一个:{}的意思是Y重复的次数,加上:3后表示P和N之间有0~3个Y

二、Re库

1、基本概念:

(1)Re库主要用于字符串匹配

(2)其采用raw string类型(原生字符串类型)

(3)采用raw string类型表示正则表达式,格式为   r'text'

eg:r'[1-9]\d{5}':由一个1~9的数和5个0~9的数组成的正则表达式

注:raw string是不包含对转义字符再次转义的字符串(如\d,在用string表示的情况下要写成\\d,但raw string没这种情况)

2、Re库主要功能函数 

学新通

(1)search():

学新通

  1.  
    import re
  2.  
    match = re.search(r'[1-9]\d{5}','BIT 100081')
  3.  
    if match:
  4.  
    print(match.group[0])
  5.  
    #输出 100081

(2)match():

学新通

  1.  
    import re
  2.  
    match = re.match(r'[1-9]\d{5}','BIT 100081')
  3.  
    if match:
  4.  
    match.group(0)
  5.  
     
  6.  
     
  7.  
    match.group(0)
  8.  
    '''因为是从头匹配,由于开头不符合匹配条件,因此匹配失败;下半部分的代码就可以匹配成功
  9.  
    Traceback (most recent call last):
  10.  
    File "<pyshell#5>", line 1, in <module>
  11.  
    match.group(0)
  12.  
    AttributeError: 'NoneType' object has no attribute 'group'
  13.  
    '''
  14.  
    match = re.match(r'[1-9]\d{5}','100081 BIT')
  15.  
    if match:
  16.  
    match.group(0)
  17.  
     
  18.  
     
  19.  
    '100081'
学新通

(3)findall():

学新通

  1.  
    import re
  2.  
    ls = re.findall(r'[1-9]\d{5}','BIT100081 TSU100084')
  3.  
    ls
  4.  
    ['100081', '100084']
  5.  
    #原理是将可以匹配的字符串存储在一个列表中

 (4)split()

学新通

  1.  
    import re
  2.  
    re.split(r'[1-9]\d{5}','BIT100081 TSU100084')#作用是去掉匹配的字符串,将剩下部分存储在列表中
  3.  
    ['BIT', ' TSU', '']
  4.  
    re.split(r'[1-9]\d{5}','BIT100081 TSU100084',maxsplit=1)#最后maxsplit=1作用是只去掉前面一个匹#配的字符串
  5.  
    ['BIT', ' TSU100084']

(5)finditer()

学新通

  1.  
    import re
  2.  
    for m in re.finditer(r'[1-9]\d{5}','BIT100081 TSU100084'):
  3.  
    if m:
  4.  
    print(m.group(0))
  5.  
     
  6.  
    # 匹配到一次返回一次
  7.  
    100081
  8.  
    100084

 (6)sub()

学新通

  1.  
    import re
  2.  
    re.sub(r'[1-9]\d{5}',':zipcode','BIT100081 TSU100084')
  3.  
    'BIT:zipcode TSU:zipcode'
  4.  
    #将所有的匹配部分换成zipcode

3、Re库另一种等价用法

学新通

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfekgg
系列文章
更多 icon
同类精品
更多 icon
继续加载