- 正则表达式是一种用来匹配字符串的强有力的工具。它的设计思想是用一种描述性的语言来给字符串定义一个规则,凡是符合规则的字符串认为合法,否则,该字符串不合法。
- re模块
myre=r"正则表达式"
print re.findall(myre,"字符串") #以列表的形式返回匹配内容,未匹配时,返回空列表
re.finditer(myre,"字符串") #返回可调用迭代器
判断满足010-12345678(以010开头,-可省略,后面是8个数字)
import re
s=raw_input("please input phonenumber:")
myre = r"^010-{0,1}\d{8}"
print re.findall(myre,s)
if __name__=="__main__":
pass
myre = r"^010-?\d{8}"
对正则表达式进行编译:
import re
s=raw_input("please input phonenumber:")
myre = r"^010-?\d{8}"
comR = re.compile(myre) #先编译模式,当正则表达式模式比较复杂的时候,会先编译,然后再使用
print re.findall(comR,s)
m=re.match(comR,s)
print m.group(0)
- re.match(p,text) :p 为正则表达式模式, text 要查找的字符串,会返回一个match 对象
- re.search(p,text) : 只要在 text 中匹配到了 p 就返回,只返回第一个匹配到的
- re.findall(p,text) :将能匹配上的全返回,会返回一个 list
- re.split(p,text) : 按照 p 匹配,并且以匹配到的字符为分隔符切割 text, 返回一个切割后的 list
- re.sub(p,s,text) : 替换,将 p 匹配到的字符替换为 s.