python正则表达式函数match()和search()的区别详解
生活随笔
收集整理的這篇文章主要介紹了
python正则表达式函数match()和search()的区别详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
match()和search()都是python中的正則匹配函數,那這兩個函數有何區別呢?
match()函數只檢測RE是不是在string的開始位置匹配, search()會掃描整個string查找匹配, 也就是說match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none。
例如:
#! /usr/bin/env python # -*- coding=utf-8 -*-import retext= 'pythontab' m= re.match(r"\w+", text) if m: print m.group(0) else:print 'not match'結果是:pythontab
而:
#! /usr/bin/env python # -*- coding=utf-8 -*- #import retext= '@pythontab' m= re.match(r"\w+", text) if m: print m.group(0) else:print 'not match'結果是:not match
search()會掃描整個字符串并返回第一個成功的匹配
例如:
#! /usr/bin/env python # -*- coding=utf-8 -*- #import retext= 'pythontab' m= re.search(r"\w+", text) if m: print m.group(0) else:print 'not match'結果是:pythontab
那這樣呢:
#! /usr/bin/env python # -*- coding=utf-8 -*- #import retext= '@pythontab' m= re.search(r"\w+", text) if m: print m.group(0) else:print 'not match'結果是:pythontab
總結
以上是生活随笔為你收集整理的python正则表达式函数match()和search()的区别详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DRF的版本和认证
- 下一篇: Python 代码混淆和加密技术