日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python正則表達式之re.match()與re.search()的用法及區別_python

作者:程序遇上智能星空 ? 更新時間: 2022-10-10 編程語言

1、re.match()的用法

re.match()方法是從起始位置開始匹配一個模式,匹配成功返回一個對象,未匹配成功返回None。

語法:

re.match(pattern, string, flags=0)

參數說明:

  • pattern:匹配的正則表達式;
  • string:要匹配的字符串;
  • flags:標志位,用于控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等;

示例如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
 
if __name__ == '__main__':
    # 匹配模式
    test_pattern = r"\d{2}年"
    # 待匹配的字符串
    test = "18年2019年2020年"
    print(re.match(test_pattern, test).group())

輸出:

18年
Process finished with exit code 0

若將匹配模式改成:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
 
if __name__ == '__main__':
    # 匹配模式
    test_pattern = r"\d{4}年"
    # 待匹配的字符串
    test = "18年2019年2020年"
    print(re.match(test_pattern, test))

則返回結果為:

None
Process finished with exit code 0

這是因為re.match()僅從頭開始匹配,由于起始位置處未找到符合匹配模式的內容,返回None。

2、re.search()的用法

re.search()方法是掃描整個字符串內進行模式匹配,只要找到第一個匹配就返回,如果字符串沒有匹配,則返回None。

語法:

re.search(pattern, string, flags=0)

參數說明:

  • pattern:匹配的正則表達式;
  • string:要匹配的字符串;
  • flags:標志位,用于控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等;

示例如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
 
if __name__ == '__main__':
    # 匹配模式
    test_pattern = r"\d{4}年"
    # 待匹配的字符串
    test = "18年2019年2020年"
    print(re.search(test_pattern, test).group())

輸出:

2019年
Process finished with exit code 0

這是因為re.search()掃描整個字符串,找到符合匹配模式的第一個匹配就返回了。

3、re.match()與re.search()的區別

re.match()方法要求必須從字符串的開頭進行匹配,如果字符串開頭不符合模式規則,整個匹配就失敗了,函數返回None;

re.search()并不要求必須從字符串的開頭進行匹配,而是掃描整個字符串,直到找到第一個匹配。

原文鏈接:https://blog.csdn.net/kevinjin2011/article/details/125598411

相關推薦

欄目分類
最近更新