python 正則表達式(一)

正則表達式(regular exprssion)是一種形式化語法描述的文本匹配模式。模式被解釋爲一組指令,而後會執行這組指令。以一個字符串做爲輸入,生成一個匹配的子集或源字符串的修改版本。正則表達式

表達式能夠包括字面量文本匹配、重複、模式組合、分支一級其餘複雜的規則。函數

  • 查找文本中的模式

re最多見的用法就是搜索文本中的模式。search()函數取模式和要草廟的文本做爲輸入,若找到這個模式則返回一個Match對象。若未找到,返回None。this

import re

parttern = 'this'
text = 'Does this text match the pattern?'

match = re.search(parttern, text)

s = match.start()
e = match.end()

print 'Found "%s"\nin "%s"\nfrom %d to %d ("%s")' % \
      (match.group(), match.string, s, e, text[s:e])

group() 顯示被匹配的字符串spa

start() end()能夠給出字符串中的相應索引,指示與模式匹配的文本在字符串中出現的位置。code

Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")

還可使用 span() 函數返回被匹配的字符串的位置(match.span())對象

相關文章
相關標籤/搜索