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())对象