import re
url = "www.baidu.com"
# 匹配包含www的字符串
re_compile = re.compile("www")
# match從起始位置開始匹配,且只匹配一次,如果不沒找到,則返回None
match = re_compile.match(url)
# .span用來獲取匹配到的字符串所對應的下標位置
#re_compile.match(url).span()
# match返回的是match對象,獲取值使用group
print(match.group())
import re
line = "Cats are smarter than dogs"
# .* 表示任意匹配除換行符(\n、\r)之外的任何單個或多個字符
matchObj = re.match(r'(.*) are (.*) .*', line, re.M | re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))
else:
print("No match!!")
D:\Python37\python.exe D:/Python-study/reTest.py
www
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter than
Process finished with exit code 0