python3中re模塊的簡單應用

前言:python3中re模塊的正則表達式,提供了re.findall(),re.search()和re.match()等常用方法來處理;本篇就來介紹一下re模塊的簡單應用。

環境:python3、sublime text3

1、匹配數字:^[0-9]*$

^表示匹配字符串的開始位置,[0-9]表示匹配0~9中的任意一個數字,*匹配前一個字符0次或無數次,$匹配字符的結束位置。總的來說就是用於匹配數字的,該數字可以是2,也可以是22222222;

<code>import re
m=re.search('^[0-9]*$','222222222222')
print('只匹配數字:',m.group())
n=re.search('^[0-9]*$','111aaa')
print('不能包括其它符號:',n.group())/<code>


python3中re模塊的簡單應用

2、匹配n位數字:^\\d{n}$

<code>import re
num=re.findall('^\\d{5}$','25255')
print('匹配幾位數字:',num)/<code>
python3中re模塊的簡單應用

3、匹配至少n位數字:^\\d{n,}$

<code>import re
m=re.findall('^\\d{3,}$','111222')
print('匹配至少大於3位數字:',m)
n=re.findall('^\\d{8,}$','111222')
print('匹配至少大於8位數字:',n)/<code>
python3中re模塊的簡單應用

4、匹配m~n的數字:^\\d{m,n}$

<code>import re
m=re.findall('^\\d{1,6}$','112233')
print('匹配1-6位數字:',m)/<code>
python3中re模塊的簡單應用

5、匹配最多帶2位小數點的數字:^([1-9][0-9]*)+(.[0-9]{1,2})?$

<code>import re
m=re.findall('^([1-9][0-9]*)+(.[0-9]{1,2})?$','112233.55')
print('匹配最多帶2位小數點的數字:',m)/<code>
python3中re模塊的簡單應用

6、匹配非0的正實數:^[1-9]\\d*$

<code>import re
m=re.findall('^[1-9]\\d*$','112233')
print('匹配非0的正實數:',m)/<code>
python3中re模塊的簡單應用

7、漢字的匹配:[\\\\u4e00-\\\\u9fa5]{1,3}

<code>import re
m="my name is 張三"
n=re.findall('[\\\\u4e00-\\\\u9fa5]{1,3}',m)
print('匹配漢字:',n)/<code>
python3中re模塊的簡單應用

8、英文和數字的匹配

<code>import re
m="我的名字叫張三,今年18歲,Hai!!"
n=re.findall('[A-Za-z0-9]+',m)
print('匹配英文和數字:',n)
p=re.findall('[A-Za-z]+',m)
print('只匹配英文字符:',p)
q=re.findall('[A-Z]+',m)
print('只匹配英文大寫字符:',q)
x=re.findall('[a-z]+',m)
print('只匹配英文小寫字符:',x)
y=re.findall('[A-Z0-9]+',m)
print('只匹配英文大寫字符和數字:',y)/<code>
python3中re模塊的簡單應用

9、中文、英文、數字和某些字符的匹配

匹配有數字、26個英文字母戶下劃線組成的字符串:\\w+

匹配中文、英文、數字、下劃線:[\\\\u4e00-\\\\u9fa5A-Za-z0-9_]+

匹配中文、英文、數字:[\\\\u4e00-\\\\u9fa5A-Za-z0-9]+

匹配輸入含有^%&',;=?$\\等字符的表達式:[^%&',;=?\\\\x22]+

<code>import re
m="我的名字叫張三,今年18歲,我的手機號:86-16888889999,我的郵箱:[email protected],Hai!!"
n=re.findall('\\w+',m)
print('匹配有數字、26個英文字母戶下劃線組成的字符串:',n)
p=re.findall('[\\\\u4E00-\\\\u9FA5A-Za-z0-9_]+',m)
print('匹配中文、英文、數字、下劃線:',p)
q=re.findall('[\\\\u4e00-\\\\u9fa5A-Za-z0-9]+',m)
print('只匹配中文、英文、數字:',q)
x=re.findall('[^%&,;=?\\\\x22]+',m)
print('匹配輸入含有^%&,;=?$\\特殊字符:',x)/<code>
python3中re模塊的簡單應用


分享到:


相關文章: