1. 程式人生 > >python裏的正則表達式

python裏的正則表達式

pytho -s groups 簡單 匹配 取模 dict upd re.sub

import re
# o = "hello meiyu abc def ads 1966"
1、# # re.match()#從頭匹配1簡單2分組
# r = re.match("h\w+",o)
#
# print(r.group())#獲取匹配到的所有結果
# r = re.match("(h\w+)",o)
# print(r.groups())#獲取模型匹配到的分組結果
# r = re.match("(?P<n1>h\w+)",o)
# print(r.groupdict())#獲取模型中匹配到的分組中所有執行了key的結果
#有分組,提取匹配成功的指定內容

2、# re.search()#瀏覽全部字符串,匹配第一個符合規則的字符串

# re.findall()#將匹配到的所有內容都放置在一個列表中
# a = re.findall("\d+\w\d+","a2c3s1d1")
# print(a)
# a = re.findall("(\d+)(\w*)(\d+)","a2c3s1d1")
# print(a)
3、# re.finditer()#叠代
# a = re.finditer("(\d+)(\w*)(\d+)","a2c3s1d1")
# print(a)
# for i in a:
# print(i,i.group(),i.groups(),i.groupdict())
4、# re.split()#分割
# a = re.split("(a\w+)",o,1)
# print(a)
# def f(ex):
# return 1
5、##計算器

# o = "1-5*(58*(4+5*(24*21/(5-2))))*55"
# while True:
# print(o)
# r = re.split("\(([^()]+)\)",o,1)#[]表示不包含
# if len(r) == 3 :
# a = r[0]
# b = r[1]
# c = r[2]#等效於a,b,c = r
# o = a + str(f(b)) + c
# else:
# print(f(o))
# break

6、# re.sub()替換
# new = re.sub("\d+","kkk",o)
# print(new)
#re.subn()
# new,count = re.subn("\d+","kkk",o)
# print(new,count)

python裏的正則表達式