Python3正則表達式:match函數

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章