Python正则表达式re模块中的函数

目录

  • findall()的使用
  • search()的使用
  • group()与groups()的使用
  • split()正则替换
  • compile的使用
  • match的使用
  • re的额外匹配要求

findall()的使用

  • findall(pattern , string, [flags])
  • 查找字符串中所有(非重复)出现的正则表达式模式,并返回一个匹配列表

search()的使用

  • search(pattern , string , flags=0)
  • 使用可选标记搜索字符串中第一次出现的正则表达式模式。如果匹配成功,则返回匹配对象如果失败,则返回None

group()与groups()

  • group(num)返回整个匹配对象,或者编号为num的特定子组
  • groups():返回一个包含所有匹配子组的元组(如果没有成功匹配,则返回一个空元组)
In [1]: test = 'hello my name is insane'

In [2]: import re

In [3]: result = re.search('hello (.*) name is (.*)', test)

In [4]: result.groups()
Out[4]: ('my', 'insane')

In [5]: result.group(1)
Out[5]: 'my'

In [6]: result.group(2)
Out[6]: 'insane'

split()正则替换

  • split(pattern, string , max=0)
  • 根据正则表达式的模式分隔符,split 函数将字符串分割为列表,然后返回成功匹配的列表,分隔最多操作max 次(默认分割所有匹配成功的位置)
In [7]: data = 'hello world'

In [8]: print(re.split('\W', data))
['hello', 'world']

re模块-match

  • match(pattern , string , flags=0)
  • 尝试使用带有可选的标记的正则表达式的模式来匹配字符串。如果匹配成功,就返回匹配对象;如果失败,就返回None。
  • match只会匹配字符串从头开始的信息,如果匹配成功,就返回匹配对象;如果失败,就返回None。
  • match返回的对象也可以使用group函数调用
In [10]: result = re.match('hello', data)

In [11]: result.groups()
Out[11]: ()

In [12]: result.group()
Out[12]: 'hello'

re模块-compile

  • compile(pattern, flags=0)
  • 定义一个匹配规则的对象
In [13]:  data='hello my email is insane@loaf.com i like python'

In [14]: re_obj = re.compile('email is (.*?) i')

In [15]: result = re_obj.findall(data)

In [16]: result
Out[16]: ['insane@loaf.com']

re的额外匹配要求

实战

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     : 2021/8/28 22:13
# @Author   : InsaneLoafer
# @File     : re_test2.py

import re


def check_url(url):
    """
    判断url是否合法
    :param url:
    :return:
    """
    re_g = re.compile('[a-zA-Z]{4,5}://\w*\.*\w+\.\w+')
    print(re_g)
    result = re_g.findall(url)
    if len(result) != 0:
        return True
    else:
        return False

def get_url(url):
    """
    通过组获取url中的某一部分
    :param url:
    :return:
    """
    re_g = re.compile('[https://|http://](\w*\.*\w+\.\w+)')
    result = re_g.findall(url)
    if len(result) != 0:
        return result[0]
    else:
        return ''

def get_email(data):
    # result = re.findall('[0-9a-zA-Z_]+@[0-9a-zA-Z]+\.[a-zA-Z]+', data)
    re_g = re.compile('.+@.+\.[a-zA-Z]+')
    result = re_g.findall(data)
    return result


html = ('<div class="s-top-nav" style="display:none;">'
        '</div><div class="s-center-box"></div>')

def get_html_data(data):
    """
    获取style中的display:
    使用非贪婪模式
    """
    re_g = re.compile('style="(.*?)"')
    result = re_g.findall(data)
    return result

def get_all_data_html(data):
    """
    获取html中所有等号后双引号内的字符
    :param data:
    :return:
    """
    re_g = re.compile('="(.+?)"')
    result = re_g.findall(data)
    return result


if __name__ == '__main__':
    result = check_url('https://www.baidu.com')
    print(result)

    result = get_url('https://www.baidu.com')
    print(result, 'https')

    result = get_url('http://www.baidu.com')
    print(result, 'http')

    result = get_email('insane@163.net')
    print(result)

    result = get_html_data(html)
    print(result)

    result = get_all_data_html(html)
    print(result)

    re_g = re.compile('\s')
    result = re_g.split(html)
    print(result)

    re_g = re.compile('<div class="(.*?)"')
    result = re_g.match(html)
    print(result)
    print(result.span())  # 返回结果的前后索引
    print(html[:22])
re.compile('[a-zA-Z]{4,5}://\\w*\\.*\\w+\\.\\w+')
True
www.baidu.com https
www.baidu.com http
['insane@163.net']
['display:none;']
['s-top-nav', 'display:none;', 's-center-box']
['<div', 'class="s-top-nav"', 'style="display:none;"></div><div', 'class="s-center-box"></div>']
<re.Match object; span=(0, 22), match='<div class="s-top-nav"'>
(0, 22)
<div class="s-top-nav"

Process finished with exit code 0
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容