import re
def start_line(mark):
print("…")
def case_match():
start_line(“match”)
result1 = re.match(‘www’,‘www.baidu.com’)
print(result1)
result2 = re.match(‘com’,‘www.baidu.com’)
print(result2)
def case_group():
start_line(“group”)
line=“Cats are smarter than dogs”
matchObj=re.search(r’(.) are (.?) .*’, line, re.M|re.I)
if matchObj:
print(matchObj.group())
print(matchObj.group(1))
print(matchObj.group(2))
print(matchObj.group())
else:
print("No match!")
def case_search():
start_line(“search”)
line=“Cats are smarter than dogs”
matchObj=re.search(r’(.) are (.?) .*’, line, re.M|re.I)
if matchObj:
print(matchObj.group())
print(matchObj.group(1))
print(matchObj.group(2))
print(matchObj.group())
else:
print("No match!")
def case_match_search():
start_line(“match and search”)
line="Cats are smarter than dogs"
matchObj=re.match(r'dog', line, re.M | re.I)
if matchObj:
print("match:",matchObj.group())
else:
print("No match!")
searchObj=re.search(r'dogs',line, re.M | re.I)
if searchObj:
print("search:",searchObj.group())
else:
print("No match!")
def case_pattern():
start_line(“pattern”)
pattern=re.compile(r’([a-z]+)([a-z]+)’, re.I)
str="Hello World!I am OK."
result=pattern.match(str)
if result:
print(result.group())
print(result.group(1))
print(result.group(2))
print(result.group())
else:
print("No match!")
def case_findall():
start_line(“findall”)
str='runoob 123 ggoole 123123123123 dsaf 321321321321'
result1=re.findall(r'\d+',str)
print(result1)
pattern= re.compile(r'\d+')
result2=pattern.findall(str)
print(result2)
result3=pattern.findall(str, 0, 10)
print(result3)
def case_finditer():
start_line(“findaiter”)
str='runoob 123 ggoole 123123123123 dsaf 321321321321'
result1=re.finditer(r'\d+', str)
print(result1)
for match in result1:
print(match.group())
def case_sub():
start_line(“sub01”)
phone="157-0675-9966 # 这是一个电话号码"
#删除注释
num=re.sub(r'#.*$',"" ,phone)
print("电话号码(无注释):",num)
#删除非数字内容
num2=re.sub(r'\D',"",phone)
print("电话号码(全数字):",num2)
def case_split():
start_line(“split”)
line='I am your father.'
print(re.split(r'\W+', line))
print(re.split(r'(\W+)',line))
print(re.split(r'\W+',line, 1))
if name == ‘main’:
case_match()
case_group()
case_search()
case_match_search()
case_pattern()
case_findall()
case_finditer()
case_sub()
case_split()