首页 > 编程语言 >Python: Regular expressions

Python: Regular expressions

时间:2024-04-28 12:00:49浏览次数:16  
标签:return Python pattern textSource re Regular print expressions match

 

    #引用库 import re 正则表达式的方式
    #1.re.compile(): 该函数用于生成一个正则表达式,也就是匹配的核心部分,用来定义你需要怎么匹配,匹配什么内容,更多细节可以去参看菜鸟教程。
    #2.re.findall(): 该函数用于在指定的字符串中进行匹配。

    #str1 = 'lukfook8-hongkong+90shenzhen-4hh h7+8facai-shanghai geovindu'
    fullname=input("please enter full name:")
    firstname=""
    lastname=""
    ls=re.split(r'[-+' '.\s]', fullname)
    #print(re.split(r'[-+' '.\s]', str1))  # 以有+(加号)、-(减号)、' '(一个空格)、.(单字节英文点号) 字符串分割
    print(type(ls))
    for s in ls:
        print(s) #循环序列出列表中的字符串
    firstname=ls[0]
    lastname=ls[1]
    print("firstname",firstname,",lastname:",lastname)

  

# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:
# 描述: 正则表达式用法
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2024/4/28 10:37
# User      : geovindu
# Product   : PyCharm
# Project   : EssentialAlgorithms
# File      : RegularString.py
# explain   : 学习

import re
import os
import sys

class DuString(object):
    """
    正则表达式用法
    """

    @staticmethod
    def strSplit(textSource: str, patterns: str):
        """
        分割字符串
        :param textSource:
        :param patterns:
        :return: list
        """
        ls = re.split(r'[' + patterns + '\s]', textSource)
        return ls

    @staticmethod
    def getdit(textSrource : str) -> list:
        """
        提取数字数据 静态方法
        所有数值
        数字提取:可以用正则表达式来提取数字,包括整数、浮点数等。
        "去商店买了8个苹果, 12斤香蕉, 共计12.85元."
        :return:
        """
        pattern = r'\d+\.\d+|\d+'
        match = re.findall(pattern, textSrource)
        if match:
            print(match)  # ['8', '12', '12.85']
        else:
            print("未找到数值")
        return match

    @staticmethod
    def getint(textSource:str) ->list:
        """
        提取整数
        :return:
        """

        # 匹配浮点数的正则表达式
        pattern = r'\d+'
        match = re.findall(pattern, textSource)
        if match:
            print(match)
        else:
            print("未找到数值")

        return match

    @staticmethod
    def getfloat(textSource:str) ->list:
        """
        提取浮点数
        :return:
        """
        # 匹配浮点数的正则表达式
        pattern = r"\d+\.\d+"

        match = re.search(pattern, textSource)
        if match:
            float_number = float(match.group())
            print(float_number)  #
        else:
            print("未找到数值")

        return match


    @staticmethod
    def getDate(textSource:str)->list:
        """
        提取日期
        处理逻辑:
            年 4位有效数值 \d{4}
            月 0-12   \d{1,2}
            日 0-31   \d{1,2}
        """
        date_text = ""
        if isinstance(textSource, str):
            regex_rule = r"(\d{4}-\d{1,2}-\d{1,2})"
            regex_pattern = re.compile(regex_rule)
            date_list = regex_pattern.findall(textSource)
            if date_list:
                date_text = date_list[0]
        return date_text

    @staticmethod
    def getTime(textSource:str)->list:
        """
        提取时间
        :param textSource:
        :return:
        """
        regexRule = r'(0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9]|0?[0-9]):([1-5][0-9]|0?[0-9])'
        regexPattern = re.compile(regexRule)
        retList = regexPattern.findall(textSource)
        if retList:
            return retList
        else:
            print('没有匹配成功.')
        return None


    @staticmethod
    def getUrl(textSource:str)->list:
        """
        提取网址
        :param textSource:
        :return:
        """
        # 定义一个正则表达式模式来匹配URL
        pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
        # 使用re.findall()函数找到所有匹配的URL
        urls = re.findall(pattern, textSource)
        return urls

    @staticmethod
    def getMainIs(textSource:str)->bool:
        """
        是否有效的邮件
        :param textSource:
        :return:
        """
        pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
        if re.match(pattern, textSource):
            print("有效的邮件地址")
            return True
        else:
            print("无效的邮件地址")
            return False


    @staticmethod
    def getIPIs(textSource:str)->bool:
        """
        是否有效的IP
        :param textSource:
        :return:
        """
        #定义IPv4地址的正则表达式
        ipv4_pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}(25[0-5]|2[0-4]\d|[01]?\d{1,2})$'
        # 定义 IPv6 地址的正则表达式
        ipv6_pattern = r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'
        if re.match(ipv4_pattern, textSource):
            print("IPv4 地址")
            return True
        elif re.match(ipv6_pattern, textSource):
            print("IPv6 地址")
            return True
        else:
            print("无效的 IP 地址")
            return False

    @staticmethod
    def getChinaMobileIs(textSource:str)->bool:
        """
        是否有效的国内手机号码
        :param textSource:
        :return:
        """
        # 匹配以1开头,第二位是3、4、5、6、7、8或9,后面有9位数字的手机号码。
        pattern = r'^1[3456789]\d{9}$'
        for number in textSource:
            if re.match(pattern, number):
                print(f'{number} 是有效的手机号码')
                return True
            else:
                print(f'{number} 不是有效的手机号码')
                return False

    @staticmethod
    def getPostCodeIs(textSource:str)->bool:
        """

        :param textSource:
        :return:
        """
        pattern = r'^\d{6}$'  # 匹配6位数字
        if re.match(pattern, textSource):
            print("邮政编码有效!")
            return True
        else:
            print("邮政编码无效!")
            return False


    @staticmethod
    def getICDIs(textSource:str)->bool:
        pattern = r'^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[0-9Xx]$'
        match = re.match(pattern, textSource)
        if match:
            print("身份证号码合法!")
            return True
        else:
            print("身份证号码不合法!")
            return False



    @staticmethod
    def extractHtmltags(textSource:str)->list:
        """

        :param textSource:
        :return:
        """
        pattern = r"<([^>]+)>"
        tags = re.findall(pattern, textSource)
        return tags


    @staticmethod
    def getStock(textSource:str)->list:
        """

        :param textSource:
        :return:
        """
        #text = "工商银行(600886)\n\t 贵州茅台(000123)"
        # 提取公司简称
        companyNamePattern = r"[\u4e00-\u9fff]+"
        companyNameMatches = re.findall(companyNamePattern, textSource)
        companyCame = companyNameMatches if companyNameMatches else None
        # 提取证券代码 6位数
        stockCodePattern = r"\d{6}"
        stockCodeMatches = re.findall(stockCodePattern, textSource)
        stockCode = stockCodeMatches if stockCodeMatches else None
        print("公司简称:", companyCame)  # 公司简称: ['工商银行', '贵州茅台']
        print("证券代码:", stockCode)  # 证券代码: ['600886', '000123']
        return companyCame,stockCode

  

 

字符

含义

举例

备注

符合条件

.

一个任意字符

a..b

a开头b结尾,中间两个任意字符

a|2b

\w

一个字母/数字/下划线

\w...

字母/数字/下划线开头

o8js

\W

非字母/数字/下划线

\Wabc

 

#abc

\s

一个空白字符

a\sb

 

a\nb

\S

一个非空白字符

\S…

三个数字

2jkh

\d

数字字符

\d\d\d

 

675

\D

非数字字符

\D\w\w\w

 

#h7_

[]

括号中任意一个字符[1-9]数字1到9 [a-z]小写 [A-Z]大写

[abc]aaa

a/b/c开头

caaa

[^字符集]

一个不在字符集中的任意字符

[^abc]...

非a/b/c开头

898i

^

字符串开头

^\ddid

 

866

$

字符串结尾

abc$

 

abc

\b

(检测边界)

Abc\b\saaa

abclb\saaa

abc aaa

*

匹配≥0次

\d*

数字0或很多次

1个或很多个数字开

12312

+

匹配≥1次

\d+abc

1个或很多个数字开头

99abc

?

匹配0/1次

a?123

有a或者无a

a123

{N}

匹配N次

 

 

 

{M,N}

匹配M到N次

 

 

 

{M,}

至少匹配M次

 

 

 

{,N}

最多匹配N次

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://docs.python.org/zh-cn/3.11//howto/regex.htmll

 

match()和search()都只匹配出一个符合条件的字符串,若想要所有,可以使用re.findall()

 

语法

释义

|

或者

()

  1. 组合(将括号中的内容作为一个整体进行操作)
  2. 捕获--使用带括号的正则表达式匹配成功后,只获取括号中的内容
  3. 重复--在正则表达式中可以通过\数字来重复前面()中匹配到的结果。数字代表前第几个分组

\

转义符号,在特殊的符号前加\,来让特殊的符号没有意义不管在哪儿都需要转义

-在口外面没有特殊功能,在口中要表示-本身,就不要放在两个字符之间()需要转义

compile

将正则表达式字符串转换成正则表达式对象

fullmatch/match

匹配对象或者None

string

获取被匹配的原字符串

findall

获取字符串中满足正则表达式的所有的子串,返回一个列表

finditer

查找所有满足正则条件的子串,返回值是迭代器,迭代器中的元素是匹配对象

split

将字符串按照满足正则表达式条件的子串进行分割

sub(正则,repl,字符串)

字符串中满足正则表达式条件的子串替换成repl。返回替换后的字符串

 

 

标签:return,Python,pattern,textSource,re,Regular,print,expressions,match
From: https://www.cnblogs.com/geovindu/p/18163427

相关文章

  • python可复用代码(连接数据库/字符串处理/爬虫/日志配置)【1】
    importpymysqlimportloggingimporttimeimportrandomimportloggingimportrequestsfrombs4importBeautifulSoup"""获取数据库连接"""#连接数据库获取游标defget_conn():""":return:连接,游标""&qu......
  • Alibaba Cloud Linux release 3 Python 3.8 安装
    AlibabaCloudLinuxrelease3Python3.8安装https://zhuanlan.zhihu.com/p/690125733背景买了台阿里云服务器玩玩,项目需要Python3.8,但是机器上配置了3.6.8机器信息:机器信息:Linuxversion5.10.134-16.1.al8.x86_64AlibabaCloudLinuxrelease3linux的多python版......
  • Python中有很多库可以操作Excel,像xlsxwriter、openpyxl、pandas、xlwings等
    Python中确实有多个库可以用于操作Excel文件,包括但不限于xlsxwriter、openpyxl、pandas和xlwings。以下是这些库的简要介绍和它们各自的优点:xlsxwriter:优点:专门用于创建新的.xlsx文件。提供了丰富的功能来创建复杂的Excel文档,包括图表、图片、自动筛选等。性能相对较......
  • 11个Python循环技巧
    本文分享自华为云社区《Python中的循环技巧指南》,作者:柠檬味拥抱。当我们处理数据时,有时候需要创建多个列表以存储不同类型或不同条件下的数据。在Python中,我们可以利用循环来快速、高效地创建这些列表。本文将介绍如何使用循环在Python中创建多个列表,并提供代码实例。python用......
  • MBIST和BISR+循环移位和强制转换+verdi操作+vip需要disable auto recording+vim设置某
    MBIST和BISRhttps://blog.csdn.net/liubin1222/article/details/103995449https://zhuanlan.zhihu.com/p/161185302进行内存修复需要两步:首先在可修复内存测试期间,由MBIST控制器诊断出的故障。第二步是修复内存,确认修复签名。可修复的存储器都有带修复签名的寄存器。MBIST(Me......
  • [Python急救站]人脸识别技术练习
    这段时间做了一个用于初学者学习人脸识别系统的程序,在上代码时,先给说说事前准备:首先我们需要一个OpenCV的一个haarcascade_frontalface_default.xml文件,只要去GitHub上面即可下载:https://github.com/opencv/opencv点击Code,选择DownloadZIP,下载后解压在目录下opencv-4.x\data\ha......
  • 攻防世界-难度1- bad_python
    the.pycisbroken,canyouhelpmerecover?攻防世界难度1-bad_pythonpython头部观察文件名pyre.cpython-36.pyc,说明是在python3.6环境下编译的,那么需要恢复正常pyc3.6对应的首部16字节。uncompyle6pip3installuncompyle6uncompyle6--versionuncompyle6pyre.cpython......
  • python题
    【Python0002】排列组合序列【题目描述】用户输入整数n(1<=n<=26)和整数m(m<=n),然后输入n个不同的字母,请编写程序输出在这n个字母中选择m个字母的所有排列序列和组合序列。【源代码程序】importitertools defgenerate_permutations_combinations(letters,m):    #生成......
  • python下载和扩展文件下载
    (三)、练习安装Python扩展库【实验截图】1、在资源管理器中进入Python安装目录的scripts子目录,然后按下Shift键,在空白处单击鼠标右键,在弹出来的菜单中选择“在此处打开命令窗口”进入命令提示符环境   2.使用pip命令在线安装Python扩展库numpy、pandas、scipy......
  • blender python api 将指定的顶点组(water)转换为颜色属性water_colors
    1.选中物体,进入权重绘制模式2.代码:importbpy#获取当前活动的物体obj=bpy.context.object#确保物体是网格类型ifobj.type!='MESH':print("当前激活的对象不是网格类型。")#exit()#使用exit()来提前退出脚本#获取名为“water”的顶点组vertex_gro......