python幾個簡單的正則使用

獲取時間

reg = '\d{4}年\d{1,2}月\d{1,2}日'
# # reg = '\d{4}年\d{2}月\d{2}日'
string = '2019年10月17日 - 論壇引起強烈反響,中國人民大學中國普惠金融研究院(CAFI)理事會聯席主席兼院長貝多廣...www.licai18.com/article/ArticleDetail.jsp?d...-快照-理財18'
x = re.search(reg, string)
print(x.group(0))

一次性替換多個字符,可以替代多次使用replace的情況,replace不再識別正則,需使用re.sub

x = 'http://www.baidu.com/li\tnk?url=NDoHHS0eqT\n\rb5aRbCL8g4LG1KiliQUoEfHseKCjd6fvjOviLO9wloiUX2zfCg2BJjJttGw5Fvvx1qXkUALc2tGmDdai_cxWVLuKfIsOh_2p_&ck=4212.2.0.0.0.360.563.0&shh=www.baidu.com'
s = re.sub('\\t|\\n|\\r', '', x)
print(s)

re.findall和re.search的區別,可以發現,()在findall裏面是和search裏作用不同,search的括號類似區分但包含

x = 'http://www.baidu.com/link?url=NDoHHS0eqTb5aRbCL8g4LG1KiliQUoEfHseKCjd6fvjO&ck=4212.2.0.0.0.360.563.0&shh=www.baidu.com'
s = re.findall('url=(.*?)&', x)  # ?非貪婪匹配 ? 0-1個
print(s)  # ['NDoHHS0eqTb5aRbCL8g4LG1KiliQUoEfHseKCjd6fvjO']
s = re.findall('url=(.*)&', x)  # 貪婪匹配
print(s)  # ['NDoHHS0eqTb5aRbCL8g4LG1KiliQUoEfHseKCjd6fvjO&ck=4212.2.0.0.0.360.563.0']
s = re.search('url=(.*?)&', x)
print(s.group(0)) #url=NDoHHS0eqTb5aRbCL8g4LG1KiliQUoEfHseKCjd6fvjO&
s = re.findall('url=.*?&', x)
print(s) #['url=NDoHHS0eqTb5aRbCL8g4LG1KiliQUoEfHseKCjd6fvjO&']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章