iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0

利用pattern較有彈性地找出字串中想要的部分

可以使用searchmatchfindall

  • match
    • checks for a match only at the beginning of the string
  • search
    • checks for a match anywhere in the string
    • pattern加上^等校於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

參考


上一篇
Day22-File-Buffer與大檔案
下一篇
Day24-re-Syntax
系列文
if len(learning.python) == 30:31

尚未有邦友留言

立即登入留言