python的re

工作中經常要和字符串打交道。匹配搜索自然少不了,這是正則表達式的強項。

直接上代碼練習。代碼示例參考這裏,講的比較詳細。


正則表達式兩種等價用法,如果在一個程序中經常用到pattern,那麼推薦使用方法1。

方法1:prog = re.compile(pattern, flag)   result = prog.match(string)

方法2:result = re.match(pattern, string)


Exp1:match

import re
pattern = re.compile(r'hello')
match = pattern.match('hello world')
if match:
  print match.group()


Exp2:search, 忽略大小寫

pattern = re.compile(r'hello', re.I)
match = pattern.search('HeLLo world')
if match:
  print match.group()


Exp3: split
pattern = re.compile(r'\d+')
res = pattern.split('one1two2three3four4')
print res 

Exp4: findall

pattern = re.compile(r'\d+')
res = pattern.findall('one1two2three3four4')
print res 

Exp5:finditer

pattern = re.compile(r'\d+')
for res in  pattern.finditer('one1two2three3four4'):
  print res.group(),



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