網站首頁 編程語言 正文
re.search()方法掃描整個字符串,并返回第一個成功的匹配。如果匹配失敗,則返回None。
與re.match()方法不同,re.match()方法要求必須從字符串的開頭進行匹配,如果字符串的開頭不匹配,整個匹配就失敗了;
re.search()并不要求必須從字符串的開頭進行匹配,也就是說,正則表達式可以是字符串的一部分。
re.search(pattern, string, flags=0)
- pattern : 正則中的模式字符串。
- string : 要被查找替換的原始字符串。
- flags : 標志位,用于控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。
例1:
import re
content = 'Hello 123456789 Word_This is just a test 666 Test'
result = re.search('(\d+).*?(\d+).*', content)
print(result)
print(result.group()) # print(result.group(0)) 同樣效果字符串
print(result.groups())
print(result.group(1))
print(result.group(2))
結果:
<_sre.SRE_Match object; span=(6, 49), match='123456789 Word_This is just a test 666 Test'>
123456789 Word_This is just a test 666 Test
('123456789', '666')
123456789
666
?
Process finished with exit code 0
例2:只匹配數字
import re
content = 'Hello 123456789 Word_This is just a test 666 Test'
result = re.search('(\d+)', content)
print(result)
print(result.group()) # print(result.group(0)) 同樣效果字符串
print(result.groups())
print(result.group(1))
結果:
<_sre.SRE_Match object; span=(6, 15), match='123456789'>
123456789
('123456789',)
123456789
?
Process finished with exit code 0
match()和search()的區別:
- match()函數只檢測RE是不是在string的開始位置匹配,
- search()會掃描整個string查找匹配
- match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none
舉例說明:
import re
print(re.match('super', 'superstition').span())
(0, 5)
print(re.match('super','insuperable'))
None
print(re.search('super','superstition').span())
(0, 5)
print(re.search('super','insuperable').span())
(2, 7)
原文鏈接:https://blog.csdn.net/m0_37360684/article/details/84140403
相關推薦
- 2022-05-17 獲取當前機器注冊到nacos上的機器ip
- 2022-12-11 React?狀態的不變性實例詳解_React
- 2022-08-12 python利用scatter繪畫散點圖_python
- 2022-01-08 React項目創建報錯解決方案npm ERR! code 1 npm ERR! path E:\No
- 2022-03-15 const定義簡單數據類型修改會報錯,而復雜數據類型則不會
- 2022-06-02 Go語言流程控制詳情_Golang
- 2022-06-04 Android實現懸浮窗效果_Android
- 2021-11-27 Linux開機自啟動服務兩種方式介紹_Linux
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支