• 【python学习】基础篇-常用模块-re模块:正则表达式高效操作字符串


    在Python中,正则表达式主要通过re模块来实现。以下是一些常用的正则表达式用法:

    匹配值:

    pattern = r'\d+'  # 匹配一个或多个数字
    pattern = r'\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b' #匹配日期格式
    pattern = r'hello'  # 匹配字符串“hello”
    
    
    • 1
    • 2
    • 3
    • 4
    • \d 表示匹配一个数字字符,等价于 [0-9];
    • +表示匹配前面的子表达式一次或多次
    • \d{4}表示匹配四位数字
    • \b 表示单词边界,确保匹配的时间字符串前后没有其他数字或字符,在字符串首尾各一个

    1、导入re模块:

    import re
    
    • 1

    2、使用re.search()函数查找字符串中是否包含指定的模式:

    import re
    pattern = r'\d+'  # 匹配一个或多个数字
    string = 'abc123def456'
    result = re.search(pattern, string)
    if result:
        print('找到匹配项:', result.group())
    else:
        print('未找到匹配项')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、使用re.findall()函数查找字符串中所有符合指定模式的子串

    import re
    pattern = r'\d+'  # 匹配一个或多个数字
    string = 'abc123def456'
    result = re.findall(pattern, string)
    print('找到的所有匹配项:', result)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4、使用re.sub()函数替换字符串中符合指定模式的子串:

    import re
    pattern = r'\d+'  # 匹配一个或多个数字
    replacement = 'NUM'
    string = 'abc123def456'
    result = re.sub(pattern, replacement, string)
    print('替换后的字符串:', result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    5、使用re.split()函数根据指定模式分割字符串

    import re
    pattern = r'\d+'  # 匹配一个或多个数字
    string = 'abc123def456'
    result = re.split(pattern, string)
    print('分割后的字符串列表:', result)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    6、使用re.compile()函数将正则表达式编译为一个模式对象,以便重复使用:

    import re
    pattern = re.compile(r'\d+')  # 匹配一个或多个数字
    
    • 1
    • 2

    7、使用re.escape()函数对特殊字符进行转义,以便在正则表达式中使用:

    import re
    string = 'a.b*c?d+e|f{g}h[i]j^k$l'
    escaped_string = re.escape(string)
    print('转义后的字符串:', escaped_string)
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    axios基本用法、axios如何发起网络请求?如何二次封装axios?
    Duchefa丨P1001植物琼脂中英文说明书
    Kubernetes禁止调度
    网络代码理解
    动环监控系统的主要功能,动环监控系统的监控对象有哪些
    网络安全(黑客)自学
    Java如何替换视频背景音乐
    框架之SpringBoot基础(一)
    了解C语言中的atoi函数和模拟实现
    启动服务提供者报 zookeeper not connected错
  • 原文地址:https://blog.csdn.net/weixin_42133116/article/details/134549254