目錄
?
?
1、正則表達式語法?
2、Python正則表達式
1>一般字符
2>字符集合
?
1、正則表達式語法?
先看圖片,大概了解一下正則表達的整體規則
2、Python正則表達式
1>一般字符
一般字符串,就是特殊制定,根據特殊的字符串進行識別
PS:python進行正則表達的一般步驟
指定好匹配的模式-pattern
選擇相應的方法-match,search等
得到匹配結果-group
設定一個輸入:input ,并導入需要的re包
import re
input = 'python學習很重要,正則表達也很重要 。 12abcABC789'
pattern = re.compile(r'正則表達')
re.findall(pattern,input)
out: ? ?['正則表達']
2>字符集合
- [abc] 指定包含字符
- [a-zA-Z] 來指定所以英文字母的大小寫
- [^a-zA-Z] 指定不匹配所有英文字母
pattern = re.compile(r'[abc]')
re.findall(pattern,input)
out: ?['a', 'b', 'c']
pattern = re.compile(r'[a-z]')
re.findall(pattern,input)
out: ??['p', 'y', 't', 'h', 'o', 'n', 'a', 'b', 'c']
pattern = re.compile(r'[a-zA-Z]')
re.findall(pattern,input)
out: ??['p', 'y', 't', 'h', 'o', 'n', 'a', 'b', 'c', 'A', 'B', 'C']
^非的用法
pattern = re.compile(r'[^a-zA-Z]')
re.findall(pattern,input)
out: ??['學',?'習',?'很',?'重',?'要',?',',?'正',?'則',?'表',?'達',?'也',?'很',?'重',?'要',?' ',?'。',?' ',?'1',?'2',?'7',?'8',?'9']
或方法
將兩個規則并列起來,以‘ | ’連接,表示只要滿足其中之一就可以匹配。
- [a-zA-Z]|[0-9] 表示滿足數字或字母就可以匹配,這個規則等價于 [a-zA-Z0-9]
pattern = re.compile(r'[a-zA-Z]|[0-9]')
re.findall(pattern,input)
out : ??['p',?'y',?'t',?'h',?'o',?'n',?'1',?'2',?'a',?'b',?'c',?'A',?'B',?'C',?'7',?'8',?'9']
匹配數字 ‘\d’ 等價于 [0-9]
pattern = re.compile(r'\d')
re.findall(pattern,input)
out: ?['1', '2', '7', '8', '9']?
‘\D’ 匹配非數字
pattern = re.compile(r'\D')
re.findall(pattern,input)
out: ?['p',?'y',?'t',?'h','o',?'n',?'學',?'習',?'很',?'重',?'要',?',',?'正',?'則',?'表',?'達',?'也',?'很',?'重',?'要',?' ',?'。',?' ',?'a',?'b',?'c',?'A',?'B','C']
‘\W’ 匹配非字母和數字
pattern = re.compile(r'\W')
re.findall(pattern,input)
out:?[',', ' ', '。', ' ']
‘\s’ 匹配間隔符
pattern = re.compile(r'\s')
re.findall(pattern,input)
out:[' ', ' ']
重復
正則式可以匹配不定長的字符串
‘*’ 0 或多次匹配
pattern = re.compile(r'\d*')
re.findall(pattern,input)
out:?['',?'',?'',?'',?'',?'',?'',?'',?'','',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'12',?'',?'',?'',?'',?'',?'',?'789',?'']
‘+’ 1 次或多次匹配
pattern = re.compile(r'\d+')
re.findall(pattern,input)
out:?['12', '789']
‘?’ 0 或 1 次匹配
pattern = re.compile(r'\d?')
re.findall(pattern,input)
out:?
['',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'',?'1',?'2',?'',?'',?'',?'',?'',?'',?'7',?'8',?'9',?'']
?
精確匹配和最小匹配?
‘{m}’ 精確匹配 m 次
pattern = re.compile(r'\d{3}')
re.findall(pattern,input)
out:?['789']
?{m,n}’ 匹配最少 m 次,最多 n 次。 (n>m)
pattern = re.compile(r'\d{1,3}')
re.findall(pattern,input)
['12', '789']
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
