正則2 匹配開頭結尾,分組轉義

匹配結尾開頭
簡單判斷email,轉義
分組

匹配結尾開頭

import re
def  main():
    names = ["age","_age","loge","age1","a_age","age_1_","age!","a#123","______"]
    for name in names:
        ret = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*",name)
        if ret:
            print ("變量名:%s 符合要求 . . .%s" % (name,ret.group()))
        else:
            print ("變量名: %s 不符合要求 . . ." % name)

if __name__ == '__main__':
    main()

在這裏插入圖片描述
可以看到age!,a#123滿足要求,按照正則邏輯應該是不滿足的。因爲match判頭不判尾 到age就結束了 後面自然打出來,那麼怎麼樣才能判頭判尾。

字符 功能
^ 匹配字符串開頭
$ 匹配字符串結尾

$加上就ok了

 ret = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*$",name)
import re
def  main():
    names = ["age","_age","loge","age1","a_age","age_1_","age!","a#123","______"]
    for name in names:
        ret = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*$",name)
        if ret:
            print ("變量名:%s 符合要求 . . .%s" % (name,ret.group()))
        else:
            print ("變量名: %s 不符合要求 . . ." % name)

if __name__ == '__main__':
    main()

在這裏插入圖片描述


簡單判斷email,轉義

判斷163郵箱地址

代碼:

import re

def main():
    email = input("請輸入一個郵箱地址:")
    ret = re.match(r"[a-zA-Z_0-9]{4,20}@163.com",email)
    if ret:
        print ("%s符合要求. . . ." % email)
    else:
        print ("%s不符合要求. . . ." % email)

if __name__ == '__main__':
    main()
注意match判頭不判尾,所以在com後面多加也會符合要求在這裏插入圖片描述
注意.com中的.

如果理解成匹配單個字符,那麼1234@163Acom也是可以的
在這裏插入圖片描述

所以這個時候需要$判尾,所以這時候需要把.轉義

\ . 前面加上反斜槓就是轉義


分組

字符 功能
| 匹配左右任意一個表達式
(ab) 將括號中字符作爲一個分組
\num 引用分組num匹配到的字符串
(?p) 分組起別名
(?P=name) 引用別名爲name分組匹配到的字符串
判斷163郵箱地址和126地址(分組可以用來取數據)
把163和126地址分組 |相當於or的作用
ret = re.match(r"[a-zA-Z_0-9]{4,20}@(163|126).com",email)
ret.group(1)  //輸出將是第一個分組裏面的數據 這個示例是163或者126
多加幾個分組
ret = re.match(r"([a-zA-Z_0-9]){4,20}@(163|126).com",email)
ret.group(1)  //輸出將是第一個分組裏面的數據 這個示例是[a-zA-Z_0-9]
ret.group(2)  //輸出將是第一個分組裏面的數據 這個示例是163或者126
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章