字元串比對和搜尋
一、 解決問題
比對或者搜尋特定模式的文本
二、解決方案
str.find(), str.endswith(), str.startswith()
re 子產品
三、代碼說明
#!/usr/bin/env python
text = 'yeah, but no, but yeah, but no, but yeah'
#完全比對
resval = text == 'yeah'
print(resval) #->False
#start or end
resval = text.startswith("yeah")
print (resval)#->True
resval = text.endswith("no")
print (resval)#->False
# find the first occurrence
resval = text.find('no')
print (resval)#->10
# 正規表達式
text1 = '11/27/2012'
text2 = 'Nov 27, 2012'
"""
match() 總是從字元串開始去比對,
如果想查找字元串任意部分的的模式出現的位置,使用findall() 方法
"""
import re
if re.match(r'\d+/\d+/\d+', text1):
print("y")
else:
print ("n")
#->y
if re.match(r'\d+/\d+/\d+', text2):
print("y")
else:
print ("n")
#->n
#将模式字元串編譯成模式對象
datepat = re.compile(r"\d+/\d+/\d+")
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
resval = datepat.findall(text)
print (resval) #->['11/27/2012', '3/13/2013']
#使用括号去捕獲分組
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
m = datepat.match("11/27/2012")
print(m)
print(m.group()) #-> 11/27/2012預設值是0
print(m.group()) #->11/27/2012
print(m.group()) #->11
print(m.group()) #->27
print(m.group()) #->2012
print(m.groups()) #->('11', '27', '2012')
month, day, year = m.groups()
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
resval = datepat.findall(text)
print (resval) #-> [('11', '27', '2012'), ('3', '13', '2013')]
for month, day, year in datepat.findall(text):
print ("{}-{}-{}".format(year, month, day))
"""
2012-11-27
2013-3-13
"""
"""
findall() 方法會搜尋文本并以清單形式方法所有的比對,
如果想以疊代方式比對,可以使用finditer()方法來代替。
"""
for m in datepat.finditer(text):
print (m) # 傳回每一個match對象,可以在match對象上調用groups來處理
# 正規表達式說明
"""
編譯對象: re.comile()
match對象: match(), finditer()
結果集:findall()
"""
"""
match 僅僅檢查字元串的開始部分
"""
m = datepat.match('11/27/2012abcdef')
print (m.group()) #->11/27/2012
"""
如果你想精确比對,確定你的正規表達式以$結尾
"""
datepat = re.compile(r'(\d+)/(\d+)/(\d+)$')
"""
忽略編譯部分(使用一次)
"""
re.findall(r'(\d+)/(\d+)/(\d+)', text)
四、關聯知識
re子產品 傳送門
五、總結
六、代碼位址
github位址:https://github.com/weichen666/python_cookbook
目錄/檔案:first_selection/learn_str_find.py