1. 程式人生 > 程式設計 >一篇文章帶你瞭解python正則表示式的正確用法

一篇文章帶你瞭解python正則表示式的正確用法

目錄
  • 正則表示式的介紹
  • re模組
  • 匹配單個字元
    • 1.匹配任意一個字元
    • 2.匹配[ ]中列舉的字元
    • 3.\d匹配數字,即0-9
    • 4.\D匹配非數字,即不是數字
    • 5.\s匹配空白,即 空格,tab鍵
    • 6.\S匹配非空白
    • 7.\w匹配非特殊字元,即a-z、A-Z、0-9、_、漢字
    • 8.\W匹配特殊字元,即非字母、非數字、非漢字
  • 總結

    正則表示式的介紹

    1)在實際開發過程中經常會有查詢符合某些複雜規則的字串的需要,比如:郵箱、手機號碼等,這時候想匹配或者查詢符合某些規則的字串就可以使用正則表示式了。

    2)正則表示式就是記錄文字規則的程式碼

    re模組

    在中需要通過正則表示式對字串進行匹配的時候,可以使用一個 re 模組

    # 匯入re模組
    www.cppcns.com
    import re # 使用match方法進行匹配操作 result = re.match(正則表示式,要匹配的字串) # 如果上一步匹配到資料的話,可以使用group方法來提取資料 result.group() # 匯入re模組 import re # 使用match方法進行匹配操作 result = re.match("test","test.cn") # 獲取匹配結果 info = result.group() print(info)

    結果:
    test

    re.match() 根據正則表示式從頭開始匹配字串資料如果第一個匹配不成功就會報錯

    匹配單個字元

    在這裡插入圖片描述

    1.匹配任意一個字元

    # 匹配任意一個字元
    import re
    
    ret = re.match(".","x"http://www.cppcns.com)
    print(ret.group())
    
    ret = re.match("t.o","too")
    print(ret.group())
    
    ret = re.match("o.e","one")
    print(ret.group())
    

    執行結果:
    x
    too
    one

    2.匹配[ ]中列舉的字元

    import re
    
    ret = re.match("[hH]","hello Python")
    print(ret.group())
    ret = rewww.cppcns.com
    .match("[hH]","Hello Python") print(ret.group())

    執行結果:
    h
    H

    3.\d匹配數字,即0-9

    import re
    
    ret = re.match("神州\d號","神州6號")
    print(ret.group())
    
    

    執行結果:
    神州6號

    4.\D匹配非數字,即不是數字http://www.cppcns.com

    non_obj = re.match("\D","s")
    print(non_obj .group())
    
    
    

    執行結果:
    s

    5.\s匹配空白,即 空格,tab鍵

    match_obj = re.match("hello\swhttp://www.cppcns.comorld","hello world")
    print(match_obj .group())
    
    

    執行結果:
    hello world

    6.\S匹配非空白

    match_obj = re.match("hello\Sworld","hello&world")
    result = match_obj.group()
    print(result)
    
    

    執行結果:
    hello&world

    7.\w匹配非特殊字元,即a-z、A-Z、0-9、_、漢字

    match_obj = re.match("\w","A")
    result = match_obj.group()
    print(result)
    
    

    執行結果:
    A

    8.\W匹配特殊字元,即非字母、非數字、非漢字

    match_obj = re.match("\W","&")
    result = match_obj.group()
    print(result)
    
    

    執行結果:
    &

    總結

    本篇文章就到這裡了,希望能給你帶來幫助,也希望您能夠多多關注我們的更多內容!