match()函數(shù)只檢測(cè)RE是不是在string的開始位置匹配, search()會(huì)掃描整個(gè)string查找匹配, 也就是說(shuō)match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none
例如:
1
2
3
4
5
6
7
8
9
10
11
|
#! /usr/bin/env python # -*- coding=utf-8 -*- import re text = 'pythontab' m = re.match(r "\w+" , text) if m: print m.group( 0 ) else : print 'not match' |
結(jié)果是:pythontab
而:
1
2
3
4
5
6
7
8
9
10
11
12
|
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = '@pythontab' m = re.match(r "\w+" , text) if m: print m.group( 0 ) else : print 'not match' |
結(jié)果是:not match
search()會(huì)掃描整個(gè)字符串并返回第一個(gè)成功的匹配
例如:
1
2
3
4
5
6
7
8
9
10
11
12
|
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = 'pythontab' m = re.search(r "\w+" , text) if m: print m.group( 0 ) else : print 'not match' |
結(jié)果是:pythontab
那這樣呢:
1
2
3
4
5
6
7
8
9
10
11
12
|
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = '@pythontab' m = re.search(r "\w+" , text) if m: print m.group( 0 ) else : print 'not match' |
結(jié)果是:pythontab
更多關(guān)于python正則函數(shù)請(qǐng)查看下面的相關(guān)文章
原文鏈接:https://www.pythontab.com/html/2013/pythonjichu_0201/199.html