1. 程式人生 > >re例子,僅供參考

re例子,僅供參考

import re
匹配字串
# pattern = re.compile(r'hello')

# match = pattern.search('ni hello cxy61!') #全字元匹配字串 .search()
# search = pattern.match('ai hello') #只在開頭匹配字串 .match()
# if match:
# print(match.group())
# else:
# print('no match.')
#
# if search:
# print(search.group())
# else:
# print('no search')


替換
time = '2017-10-01'
pattern = re.compile(r'\D') #匹配非數字的字元
sub = pattern.sub('/',time) #替換非數字的字元
print(sub)
print(re.sub(r'\D','/',time)) #也可以這樣寫,re.sub(表示式,替換字元,內容)
#\D非數字的,'/'替換字元,time目標;把time裡面非數字的都替換為/