python 正則表達式三

#分組能滿足一些特定得需求
#re.match無分組
test = "good morning this is time 10"
test1 = re.match("g\w+",test)
print(test1.group()) #good #返回匹配的所有結果
print(test1.groups()) #()#獲取模型中匹配到的分組結果
print(test1.groupdict()) #()#獲取模型中匹配到分組中所有執行key的組
# #re.match有分組()
test = "good morning this is time 10"
test1 = re.match("g(?P<m1>\w+)",test)
print(test1.group())  #good
print(test1.groups()) #('g', 'ood')
print(test1.groupdict()) #{'m1': 'ood'}

#re.serch無分組
test = "good morning this is time 10"
test1 = re.search("m\w+",test)
print(test1.group()) #morning
print(test1.groups())
print(test1.groupdict())
#re.serch有分組
test = "good morning this is time 10"
test1 = re.search("m(\w+).*(?P<n1>\d)$",test)
print(test1.group()) #morning this is time 10
print(test1.groups()) #('orning', '0')
print(test1.groupdict()) #{'n1': '0'}

#findall,fileiter.split
test = "good morning this is time 10"
test1 = re.findall("t(\w+)",test)
print(test1)    #['his', 'ime']
test1 = re.findall("(t)(\w+)",test)
print(test1)    #[('t', 'his'), ('t', 'ime')]
test1 = re.findall("(t)((\w+)(i))(s)",test) #[('t', 'hi', 'h', 'i', 's')]
print(test1)    #[('t', 'hi', 'h', 'i', 's')]
test2 = re.finditer("m(\w+)(ng)",test)
for i in test2:
    print(i.group(),i.groups(),i.groupdict())
print(re.split("m\w+",test)) #['good ', ' this is ti', ' 10']
print(re.split("(m\w+)",test)) #['good ', 'morning', ' this is ti', 'me', ' 10']
print(re.split("(m\w+)",test)) #['good ', 'morning', ' this is ti', 'me', ' 10']#只分割一次
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章