利用pattern
較有彈性地找出字串中想要的部分
可以使用search
、match
和findall
^
等校於match兩者相同的部分在於若有match則會傳回match object
,若無則回傳None
import re
s = 'purple abc.lin@google.com monkey dishwasher'
match = re.search(r'\w+@\w+', s)
if match:
print(match.group())
else:
print('Not match')
# lin@google
match2 = re.search(r'[\w.-]+@[\w.-]+', s)
if match2:
print(match2.group())
else:
print('Not match')
# abc.lin@google.com
s2 = 'red abc.lin@google.com monkey dishwasher cde.chen@google.com'
match3 = re.match(r'[\w.-]+@[\w.-]+', s2)
if match3:
print(match3.group())
else:
print('Not match')
# Not match
match4 = re.search(r'[\w.-]+@[\w.-]+', s2)
if match4:
print(match4.group())
else:
print('Not match')
# abc.lin@google.com
match5 = re.findall(r'[\w.-]+@[\w.-]+', s2)
for idx, mail in enumerate(match5):
print("{}:{}".format(idx, mail))
# 0:abc.lin@google.com
# 1:cde.chen@google.com