介紹
import re
-----regular expression
前提:
處理的是字符串
效果:
學(xué)習(xí)語(yǔ)法規(guī)則蕴掏,按照設(shè)定的額規(guī)則零酪,對(duì)字符串提取指定內(nèi)容
按照模板取字符串的指定內(nèi)容
findall()
找到所有的,返回列表隙咸;若沒(méi)找到,返回空列表
re.findall(pattern,=,string=,flags=)
pattern 正則表達(dá)式即制定匹配規(guī)則
string 要處理的字符串
flags
舉例1
import re
res = re.findall('1', '12321')
print(res)
['1', '1']
舉例2
res1 = re.findall('5', '12321')
print(res1)
[]
舉例3 flags
res2 = re.findall('p', 'Python你愛(ài)不愛(ài)python',flags=re.I)
flags=re.I 忽略大小寫
print(res2)
['P', 'p']
匹配單個(gè)字符
1. . : 匹配任意1個(gè)字符(除了\n)
2. [] : 匹配[ ]中列舉的一個(gè)字符
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ù)字榆浓,非漢字于未,非下劃線
舉例
import re
# 1. . : 匹配任意1個(gè)字符(除了\n)
# res = re.findall('h', 'python hello')
# print(res) # ['h', 'h']
# res = re.findall('.', 'python hello')
# print(res) # ['p', 'y', 't', 'h', 'o', 'n', ' ', 'h', 'e', 'l', 'l', 'o']
# 2.[]: 匹配[]中列舉的一個(gè)字符
res = re.findall('[Hl]', 'Hello haha')
print(res) # ['H', 'l', 'l']
# 匹配0-9
res = re.findall('[0123456789]hello python', '9hello python')
print(res)
res = re.findall('[0-9]hello python', '9hello python')
print(res) # ['9hello python']
# 取0-9但不要4
res = re.findall('[0-35-9]hello python', '4hello python')
print(res) # []
# 3. \d : 匹配數(shù)字,即0-9
res = re.findall('今天是8號(hào)', '今天是8號(hào)嗎')
print(res) # ['今天是8號(hào)']
res = re.findall('今天是8號(hào)', '今天難道是8號(hào)嗎')
print(res) # []
res = re.findall(r'\d', '123')
print(res) # ['1', '2', '3']
# 6. \S : 匹配非空白
# res = re.findall(r'\S', ' hkyx123 ')
# print(res) # ['h', 'k', 'y', 'x', '1', '2', '3']
# 7. \w : 匹配單詞字符陡鹃,即a-z烘浦,A-Z,0-9萍鲸,_ 闷叉,漢字
# res = re.findall(r'\w','djksalgfdw3pt哈哈')
# print(res) # ['d', 'j', 'k', 's', 'a', 'l', 'g', 'f', 'd', 'w', '3', 'p', 't', '哈', '哈']