如何使用正则表达式sys.re
# -*- coding:utf-8 -*-
import re
# use the ^ and $
s = "HELLO WORLD"
print re.findall(r"^hello",s)
print re.findall(r"^hello",s,re.I)
print re.findall("WORLD$",s)
print re.findall(r"wORld$",s,re.I)
print re.findall(r"\b\w+\b",s)
[]
['HELLO']
['WORLD']
['WORLD']
['HELLO', 'WORLD']
# -*- coding:utf-8 -*-
import re
# replace the string
s = "hello world"
print re.sub("hello","hi",s)
print re.sub("hello","hi",s[-4:])
print re.sub("world","China",s[-5:])
hi world
orld
China
# -*- coding:utf-8 -*-
import re
# use the special character
s = "嗨 WORLD2"
print "replace char: "+re.sub(r"\w","hi",s)
print "match times: "+str(re.subn(r"\w", "hi", s)[1])
print "replace nonumchar: "+re.sub(r"\W", "hi", s)
print "match times: "+str(re.subn(r"\W", "hi", s)[1])
print "replace blank: "+re.sub(r"\s", "* ", s)
print "match times: "+str(re.subn(r"\s", "*", s)[1])
print "replace nonblankchar: "+re.sub(r"\S","hi",s)
print "match times: "+str(re.subn(r"\S", "hi", s)[1])
print "replace num: "+re.sub(r"\d", "2.0", s)
print "match times: "+str(re.subn(r"\d", "2.0", s)[1])
print "replace nonum: "+re.sub(r"\D", "hi", s)
print "match times: "+str(re.subn(r"\D", "hi", s)[1])
print "replace anychar: "+re.sub(r".", "hi", s)
print "match times: "+str(re.subn(r".", "hi", s)[1])
replace char: 嗨 hihihihihihi
match times: 6
replace nonumchar: hihihihiWORLD2
match times: 4
replace blank: 嗨* WORLD2
match times: 1
replace nonblankchar: hihihi hihihihihihi
match times: 9
replace num: 嗨 WORLD2.0
match times: 1
replace nonum: hihihihihihihihihi2
match times: 9
replace anychar: hihihihihihihihihihi
match times: 10
# -*- coding:utf-8 -*-
import re
# use the qualifier
tel1 = "0791-1234567"
print re.findall(r'\d{3}-\d{8}|\d{4}-\d{7}', tel1)
tel2 = "010-12345678"
print re.findall(r'\d{3}-\d{8}|\d{4}-\d{7}', tel2)
tel3 = "(010)12345678"
print re.findall(r'[\(]?\d{3}[\)-]?\d{8}|[\(]?\d{4}[\)-]?\d{7}', tel3)
['0791-1234567']
['010-12345678']
['(010)12345678']
什么是正则表达式sys.re
正则表达式用于搜索、替换和解析字符串。
Python提供了re模块实现正则表达式的验证。