正则表达式的应用

2019-08-11  本文已影响0人  TTTRX

匹配5分钟前,2小时前等

import re
matchRule=re.compile(r'.*分钟前')
test=["5分钟前","刚刚"]
for item in test:
    if matchRule.match(item):
        print("OK")
    else:
        print("No")

r'.*分钟前'表达的意思是前面不管有多少字符,只要最后面有“分钟前”就算匹配成功。

提取“2天前”,“3天前”中的数字

def weekMatch(theStr):
    if(re.match(r'\d天前',theStr)):
        return True
    return False


test=["5分钟前","刚刚","1天前"]
for item in test:
    if weekMatch(item):
        result=re.findall(r'\d',item)
        # findall返回的是一个list
        print(int(result[0]))
        
    else:
        print("No")

支付宝红包码,你领红包我赚赏金;土豪请任意收钱码打赏
上一篇 下一篇

猜你喜欢

热点阅读