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

學無先后,達者為師

網站首頁 編程語言 正文

Python3?re.search()方法的具體使用_python

作者:Rustone ? 更新時間: 2022-10-10 編程語言

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

欄目分類
最近更新