Python 正則學習(一)

1. Match() 和 Search() 的區別:

    match試圖從字符串起始部分匹配,search不但會搜索字符中字符串中的第一次出現的位置,而且嚴格的從左往右搜索

m = re.match('foo', 'seafood')  #匹配失敗
if m is not None:
    print(m.group())
m = re.search('foo', 'seafood')
if m is not None:
    print(m.group())    #foo

2. 創建字符集([ ])

bt = '[cr][23][dp][o2]'
m = re.match(bt, 'c3po')
if m is not None:
    print(m.group()) ##c3po

3. 匹配多個字符串 (|)

bt = 'bat|bet|bit'
m = re.match(bt, 'bat')
if m is not None:
    print(m.group())  # bat

4. 分組

m = re.match('(\w\w\w)-(\d\d\d)', 'abc-123')
if m is not None:
    print(m.group())  # abc-123
    print(m.group(1))  # abc
    print(m.group(2))  # 123
    print(m.groups())  # ('abc', '123')

5. findall()

m = re.findall('car', 'carry the barcardi to the car')
if m is not None:
    print(m) # ['car', 'car', 'car']




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章