python 學習 -- 正規表示式的使用

xiaopengyaonixi發表於2016-10-23
import re

# 分割字串的用法
t = 'a b   c'.split(' ')
print(t)

t1 = re.split(r'\s+','a b  c')
print(t1)

t2 = re.split(r'[\s\,]+','a,b, c')
print(t2)

t3 = re.split(r'[\s\,\;]+','a b ;;;  d , d,,sd')
print(t3)


# 分組的用法
m = re.match(r'^(\d{3})-(\d{3,8})$','010-12345')
print(m)

print(m.group(0))
print(m.group(1))
print(m.group(2))


# 貪婪匹配
print(re.match(r'^(\d+)(0*)$','102300').groups())
# 非貪婪匹配加一個?
print(re.match(r'^(\d+?)(0*)$','102300').groups())

# 編譯表示式
# 當我們在python中使用正則時,re會幹兩件事情:
# 1.編譯正規表示式,如果表示式本身有錯誤會報錯
# 2.用編譯後的正規表示式去匹配字串

re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
print("--->",re_telephone.match('010-123443'))


相關文章