正則表達式(2) -限定字符
限定字符的意思-限制我們要搜尋的字符範圍
常見的符號如下
| 限定符 | 含义 |
|---|---|
| * | 重复零次或多次 |
| + | 重复一次或多次 |
| ? | 重复零次或一次 |
| {n} | 重复n次 |
| {n,} | 重复n次或更多次 |
| {n,m} | 重复n次到m次 {1,3} |
import re
#假設我現在要找字串裡的數字,讓它以2個字一組印出
strWord='sanckqdcpoNVA;KCD@121223R3QJ!#$@$'
s=re.findall('\d{2}',strWord)
得到的結果如下
PS D:\python> & C:/Python38/python.exe d:/python/test3.py
['12', '12', '23']
import re
#假設我現在要找字串裡的數字,讓它以5個字或更多為一組印出
strWord='sanckqdcpoNVA;KCD@121223R3QJ!#$@$'
s=re.findall('\d{5,}',strWord)
print(s)
得到結果如下
PS D:\python> & C:/Python38/python.exe d:/python/test3.py
['121223']
import re
#那麼用0-9a-z來批配,以3一組,可以寫成如下
strWord='sanckqdcpoNVA;KCD@121223R3QJ!#$@$'
s=re.findall('[0-9a-z]{3}',strWord)
print(s)
得到結果如下
['san', 'ckq', 'dcp', '121', '223']
如果要查找字串裡的IP位址,要如何批配呢?
假設我查到我IP是如下
ip='您的IP如下: 192.168.43.52 , 192,147.1.1, 123.45.83.23'
那我可以利用'\d{3}.\d+.\d+.\d+'來批配,\d{3}的意思是前面要3組數字為一組
\d+為數字後面可重覆一次或多次,+號可參照最上表裡註明
import re
ip='您的IP如下: 192.168.43.52 , 192,147.1.1, 123.45.83.23'
result=re.findall('\d{3}.\d+.\d+.\d+', ip)
print(result)
結果如下:
PS D:\python> & C:/Python38/python.exe d:/python/test3.py
['192.168.43.52', '192,147.1.1', '123.45.83.23']
沒有留言:
張貼留言