re正則匹配re.match()


前言

re.match 嘗試從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。
re.search 掃描整個字符串並返回第一個成功的匹配。

re.match

使用語法:

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

函數參數說明:

  • pattern 匹配的正則表達式
  • string 要匹配的字符串。
  • flags 標志位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。參見:正則表達式修飾符,可選標志

match 使用示例

從起始位置開始匹配,沒匹配到返回None

import re # 在起始位置匹配
r1 = re.match("hello", "hello world!") # 不在起始位置匹配
r2 = re.match("world", "hello world!") print(r1) #返回match對象
print(r1.group()) print(r2)

運行結果

<re.Match object; span=(0, 5), match='hello'> hello None

其他基礎寫法

import re # 基礎寫法二
str_c=re.compile('hello') r1=str_c.match('hello,world') print(r1.group()) #基礎寫法三
str_c=re.compile('hello') r2=re.match(str_c,'hello,world') print(r2.group())

 

運行結果

hello
hello

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM