目錄
- 正則表達式的介紹
- re模塊
- 匹配單個字符
- 1.匹配任意一個字符
- 2.匹配[ ]中列舉的字符
- 3.\d匹配數(shù)字,即0-9
- 4.\D匹配非數(shù)字,即不是數(shù)字
- 5.\s匹配空白,即 空格,tab鍵
- 6.\S匹配非空白
- 7.\w匹配非特殊字符,即a-z、A-Z、0-9、_、漢字
- 8.\W匹配特殊字符,即非字母、非數(shù)字、非漢字
- 總結
正則表達式的介紹
1)在實際開發(fā)過程中經(jīng)常會有查找符合某些復雜規(guī)則的字符串的需要,比如:郵箱、手機號碼等,這時候想匹配或者查找符合某些規(guī)則的字符串就可以使用正則表達式了。
2)正則表達式就是記錄文本規(guī)則的代碼
re模塊
在Python中需要通過正則表達式對字符串進行匹配的時候,可以使用一個 re 模塊
# 導入re模塊
import re
# 使用match方法進行匹配操作
result = re.match(正則表達式,要匹配的字符串)
# 如果上一步匹配到數(shù)據(jù)的話,可以使用group方法來提取數(shù)據(jù)
result.group()
# 導入re模塊
import re
# 使用match方法進行匹配操作
result = re.match("test","test.cn")
# 獲取匹配結果
info = result.group()
print(info)
結果:
test
re.match() 根據(jù)正則表達式從頭開始匹配字符串數(shù)據(jù)如果第一個匹配不成功就會報錯
匹配單個字符

1.匹配任意一個字符
# 匹配任意一個字符
import re
ret = re.match(".","x")
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 = re.match("[hH]","Hello Python")
print(ret.group())
運行結果:
h
H
3.\d匹配數(shù)字,即0-9
import re
ret = re.match("神州\d號","神州6號")
print(ret.group())
運行結果:
神州6號
4.\D匹配非數(shù)字,即不是數(shù)字
non_obj = re.match("\D", "s")
print(non_obj .group())
運行結果:
s
5.\s匹配空白,即 空格,tab鍵
match_obj = re.match("hello\sworld", "hello world")
print(match_obj .group())
運行結果:
hello world
6.\S匹配非空白
match_obj = re.match("hello\Sworld", "helloworld")
result = match_obj.group()
print(result)
運行結果:
helloworld
7.\w匹配非特殊字符,即a-z、A-Z、0-9、_、漢字
match_obj = re.match("\w", "A")
result = match_obj.group()
print(result)
運行結果:
A
8.\W匹配特殊字符,即非字母、非數(shù)字、非漢字
match_obj = re.match("\W", "")
result = match_obj.group()
print(result)
運行結果:
總結
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
您可能感興趣的文章:- python演示解答正則為什么是最強文本處理工具
- 一篇文章帶你了解Python和Java的正則表達式對比
- 一篇文章徹底搞懂python正則表達式
- 超詳細講解python正則表達式
- Python正則表達式保姆式教學詳細教程
- 帶你精通Python正則表達式
- Python正則表達式中的量詞符號與組問題小結
- Python正則表達式的應用詳解
- 淺談Python中的正則表達式
- python正則表達式re.search()的基本使用教程
- python正則表達式函數(shù)match()和search()的區(qū)別