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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python中使用正則表達(dá)式的方法詳解_python

作者:coding白 ? 更新時(shí)間: 2022-06-01 編程語言

在python中使用正則表達(dá)式,主要通過下面的幾個(gè)方法

search(pattern, string, flags=0)

  • 掃描整個(gè)string并返回匹配pattern的結(jié)果(None或?qū)ο?
  • 有匹配的字符串的話返回一個(gè)對象(包含符合匹配條件的第一個(gè)字符串),否則返回None
import re
#導(dǎo)入正則庫

content = 'Hello 1234567 Hello 666'
#要匹配的文本
res = 'Hello\s'
#正則字符串

result = re.search(res, content)
if result is not None:
    print(result.group())
    #輸出匹配得到的字符串 'hello'(返回的得是第一個(gè)'hello')
       
print(result.span())
#輸出輸出匹配的范圍(匹配到的字符串在原字符串中的位置的范圍)

res1 = 'Hello\s(\d)(\d+)'
result = re.search(res1, content)
print(result.group(1))
#group(1)表示匹配到的第一個(gè)組(即正則字符串中的第一個(gè)括號)的內(nèi)容
print(result.group(2))

findall(pattern, string, flags=0)

  • 掃描整個(gè)context并返回匹配res的結(jié)果(None或列表)
  • 有匹配的字符串的話返回一個(gè)列表(符合匹配條件的每個(gè)子字符串作為它的一個(gè)元素),否則返回None
import re

res = 'Hello\s'
results = re.findall(res, content)
if results is not None:
   print(results)
   #輸出: ['hello','hello']

res1 = 'Hello\s(\d)(\d+)'
results = re.findall(res1, content)
if result is not None:
    print(results) 
    # 當(dāng)正則字符串中出現(xiàn)括號時(shí),所得到列表的每個(gè)元素是元組
    # 每個(gè)元組的元素都是依次匹配到的括號內(nèi)的表達(dá)式的結(jié)果
    #輸出: [('1','1234567'),('6','666')]

sub(pattern, repl, string, count=0, flags=0)

  • 可以來修改文本
  • 用將用pattern匹配string所得的字符串替換成repl
import re

content = '54aK54yr5oiR54ix5L2g'
res = '\d+'
content = re.sub(res, '', content)
print(content)

compile(pattern, flags=0)

將正則表達(dá)式res編譯成一個(gè)正則對象并返回,以便復(fù)用

import re

content1 = '2019-12-15 12:00'
content2 = '2019-12-17 12:55'
content3 = '2019-12-22 13:21'
pattern = re.compile('\d{2}:\d{2}')
result1 = re.sub(pattern, '', content1)
result2 = re.sub(pattern, '', content2)
result3 = re.sub(pattern, '', content3)
print(result1, result2, result3)

flags的一些常用值

  • re.I 使匹配對大小寫不敏感
  • re.S 使.匹配包括換行符在內(nèi)的所有字符
import re
re.compile(res, re.I)
#如果res可以匹配大寫字母,那它也可以匹配相應(yīng)的小寫字母,反之也可

re.compile(res,re.S)
#使res中的'.'字符可以匹配包括換行符在內(nèi)的所有字符

總結(jié)

原文鏈接:https://blog.csdn.net/qq_50864152/article/details/123796723

欄目分類
最近更新