匹配正則 正規表示式 單個字元匹配

2021-10-16 03:10:26 字數 2934 閱讀 6619

通過re模組能夠完成使用正規表示式來匹配字串

**功能.匹配任意1個字元(除了)[ ]匹配[ ]中列舉的字元d匹配數字,即0-9d匹配非數字,即不是數字s匹配空白,即 空格,tab鍵s匹配非空白w匹配非特殊字元,即a-z、a-z、0-9、_、漢字w匹配特殊字元,即非字母、非數字、非漢字

import reret = re.match(".","m")print(ret.group())ret = re.match("t.o","too")print(ret.group())ret = re.match("t.o","two")print(ret.group())
執行結果:

mtootwo
import re# 如果hello的首字元小寫,那麼正規表示式需要小寫的hret = re.match("h","hello python")print(ret.group())# 如果hello的首字元大寫,那麼正規表示式需要大寫的hret = re.match("h","hello python")print(ret.group())# 大小寫h都可以的情況ret = re.match("[hh]","hello python")print(ret.group())ret = re.match("[hh]","hello python")print(ret.group())ret = re.match("[hh]ello python","hello python")print(ret.group())# 匹配0到9第一種寫法ret = re.match("[0123456789]hello python","7hello python")print(ret.group())# 匹配0到9第二種寫法ret = re.match("[0-9]hello python","7hello python")print(ret.group())ret = re.match("[0-35-9]hello python","7hello python")print(ret.group())# 下面這個正則不能夠匹配到數字4,因此ret為noneret = re.match("[0-35-9]hello python","4hello python")# print(ret.group())
執行結果:

hhhhhello python7hello python7hello python7hello python
import re# 普通的匹配方式ret = re.match("嫦娥1號","嫦娥1號發射成功")print(ret.group())ret = re.match("嫦娥2號","嫦娥2號發射成功")print(ret.group())ret = re.match("嫦娥3號","嫦娥3號發射成功")print(ret.group())# 使用d進行匹配ret = re.match("嫦娥d號","嫦娥1號發射成功")print(ret.group())ret = re.match("嫦娥d號","嫦娥2號發射成功")print(ret.group())ret = re.match("嫦娥d號","嫦娥3號發射成功")print(ret.group())
執行結果:

嫦娥1號嫦娥2號嫦娥3號嫦娥1號嫦娥2號嫦娥3號
import rematch_obj = re.match("d", "f")if match_obj:    # 獲取匹配結果    print(match_obj.group())else:    print("匹配失敗")
執行結果:

f
import re# 空格屬於空白字元match_obj = re.match("hellosworld", "hello world")if match_obj:    result = match_obj.group()    print(result)else:    print("匹配失敗")#  屬於空白字元match_obj = re.match("hellosworld", "helloworld")if match_obj:    result = match_obj.group()    print(result)else:    print("匹配失敗")
執行結果:

hello worldhello world
import rematch_obj = re.match("hellosworld", "hello&world")if match_obj:result = match_obj.group()print(result)else:print("匹配失敗")match_obj = re.match("hellosworld", "hello$world")if match_obj:result = match_obj.group()print(result)else:print("匹配失敗")
執行結果:

hello&world  hello$world
import re# 匹配非特殊字元中的一位match_obj = re.match("w", "a")if match_obj:    # 獲取匹配結果    print(match_obj.group())else:    print("匹配失敗")
執行結果:

a
# 匹配特殊字元中的一位match_obj = re.match("w", "&")if match_obj:    # 獲取匹配結果    print(match_obj.group())else:    print("匹配失敗")
執行結果:

&

正規表示式 匹配多個字元

功能 匹配前乙個字元出現0次或者無限次,即可有可無 匹配前乙個字元出現1次或者無限次,即至少有1次 匹配前乙個字元出現1次或者0次,即要麼有1次,要麼沒有 匹配前乙個字元出現m次 匹配前乙個字元出現從m到n次 需求 匹配出乙個字串第乙個字母為大小字元,後面都是小寫字母並且這些小寫字母可 有可無 im...

正規表示式2 匹配單個字元

正規表示式可以只包含純文字 1 有多個匹配結果 絕大多數正規表示式引擎的預設行為是只返回第1個匹配結果,但是根據具體的實現,提供了不同的方法把所有的匹配結果全部找出來。2 字母的大小寫問題 正規表示式是區分大小寫的。具體實現可通過標誌來強制進行不區分大小寫。正規表示式的特殊字元用於給出要搜尋的東西。...

正規表示式1(匹配單個字元)

函式功能 preg grep 執行搜尋並以陣列形式返回匹配結果 findall 查詢所有子串並以列表形式將其返回 finditer 查詢所有子串並以迭代器形式將其返回 match 在字串的開頭執行正規表示式搜尋 search 搜尋字串中的所有匹配項 split 將字串轉換成列表,在模式匹配的地方將其...