1. 程式人生 > >python3 正則匹配 re.split,re.finditer,re.findall 方法

python3 正則匹配 re.split,re.finditer,re.findall 方法

re.split re.finditer re.findall

@(python3)

re.compile() 函式

編譯正則表示式模式,返回一個物件。可以把常用的正則表示式編譯成正則表示式物件,方便後續呼叫及提高效率。
re 模組最離不開的就是 re.compile 函式。其他函式都依賴於 compile 建立的 正則表示式物件

re.compile(pattern, flags=0)
  • pattern 指定編譯時的表示式字串
  • flags 編譯標誌位,用來修改正則表示式的匹配方式。支援 re.L|re.M 同時匹配

flags 標誌位引數

re.I
(re.IGNORECASE) 使匹配對大小寫不敏感 re.L(re.LOCAL) 做本地化識別(locale-aware)匹配 re.M(re.MULTILINE) 多行匹配,影響 ^ 和 $ re.S(re.DOTALL) 使 . 匹配包括換行在內的所有字元 re.U(re.UNICODE) 根據Unicode字符集解析字元。這個標誌影響 \w, \W, \b, \B. re.X(re.VERBOSE) 該標誌通過給予你更靈活的格式以便你將正則表示式寫得更易於理解。

示例:

import re

content = 'Citizen wang , always fall in love with neighbour,WANG'
rr = re.compile(r'wan\w', re.I) # 不區分大小寫 print(type(rr)) a = rr.findall(content) print(type(a)) print(a)

findall 返回的是一個 list 物件

<class '_sre.SRE_Pattern'>
<class 'list'>
['wang', 'WANG']

re.split 函式

按照指定的 pattern 格式,分割 string 字串,返回一個分割後的列表。

re.split(pattern, string, maxsplit=0
, flags=0)
  • pattern compile 生成的正則表示式物件,或者自定義也可
  • string 要匹配的字串
  • maxsplit 指定最大分割次數,不指定將全部分割
import re

str = 'say hello world! hello python'
str_nm = 'one1two2three3four4'
pattern = re.compile(r'(?P<space>\s)') # 建立一個匹配空格的正則表示式物件
pattern_nm = re.compile(r'(?P<space>\d+)') # 建立一個匹配空格的正則表示式物件
match = re.split(pattern, str)
match_nm = re.split(pattern_nm, str_nm, maxsplit=1)
print(match)
print(match_nm)

結果:

['say', ' ', 'hello', ' ', 'world!', ' ', 'hello', ' ', 'python']
['one', '1', 'two2three3four4']

re.findall() 方法

返回一個包含所有匹配到的字串的列表

  • pattern 匹配模式,由 re.compile 獲得
  • string 需要匹配的字串
import re

str = 'say hello world! hello python'
pattern = re.compile(r'(?P<first>h\w)(?P<symbol>l+)(?P<last>o\s)') # 分組,0 組是整個 world!, 1組 or,2組 ld!
match = re.findall(pattern, str)
print(match)

結果

[('he', 'll', 'o '), ('he', 'll', 'o ')]

re.finditer 、re.findall

re.finditer(pattern, string[, flags=0])

re.findall(pattern, string[, flags=0])
  • pattern compile 生成的正則表示式物件,或者自定義也可
  • string 要匹配的字串

findall 返回一個包含所有匹配到的字元的列表,列表類以元組的形式存在。

finditer 返回一個可迭代物件。

示例一:

pattern = re.compile(r'\[email protected]\w+.com')   #通過 re.compile 獲得一個正則表示式物件

result_finditer = re.finditer(pattern, content)  
print(type(result_finditer)) 
print(result_finditer) # finditer 得到的結果是個可迭代物件
for i in result_finditer:  # i 本身也是可迭代物件,所以下面要使用 i.group()
    print(i.group())

result_findall = re.findall(pattern, content)
print(type(result_findall))  # findall 得到的是一個列表
print(result_findall)
for p in result_finditer:
    print(p)

輸出結果:

<class 'callable_iterator'>
<callable_iterator object at 0x10545ec88>
123456@163.com
234567@163.com
345678@163.com
<class 'list'>
['[email protected]', '[email protected]', '[email protected]']

由結果可知:finditer 得到的是可迭代物件,finfdall 得到的是一個列表。

示例二:

import re

content = '''email:[email protected]
email:[email protected]
email:[email protected]
'''
pattern = re.compile(r'(?P<number>\d+)@(?P<mail_type>\w+).com')
result_finditer = re.finditer(pattern, content)
print(type(result_finditer))
print(result_finditer)
iter_dict = {}   # 把最後得到的結果
for i in result_finditer:
    print('郵箱號碼是:', i.group(1),'郵箱型別是:',i.group(2))
    number = i.group(1)
    mail_type = i.group(2)
    iter_dict.setdefault(number, mail_type)  # 使用 dict.setdefault 建立了一個字典
print(iter_dict)

print('+++++++++++++++++++++++++++++++')

result_findall = re.findall(pattern, content)
print(result_findall)
print(type(result_findall))

輸出結果:

<class 'callable_iterator'>
<callable_iterator object at 0x104c5cbe0>
郵箱號碼是: 123456 郵箱型別是: 163
郵箱號碼是: 234567 郵箱型別是: 163
郵箱號碼是: 345678 郵箱型別是: 163
{'123456': '163', '234567': '163', '345678': '163'}
+++++++++++++++++++++++++++++++
[('123456', '163'), ('234567', '163'), ('345678', '163')]
<class 'list'>

finditer 得到的可迭代物件 i,也可以使用 lastindex,lastgroup 方法。

print('lastgroup 最後一個被捕獲的分組的名字',i.lastgroup)
  1. findall 當正則沒有分組,返回就是正則匹配。
re.findall(r"\[email protected]\w+.com", content)
['[email protected]', '[email protected]', '[email protected]']
  1. 有一個分組返回的是分組的匹配
re.findall(r"(\d+)@\w+.com", content)
['2345678', '2345678', '345678']
  1. 多個分組時,將結果作為 元組,一併存入到 列表中。
re.findall(r"(\d+)@(\w+).com", content)
[('2345678', '163'), ('2345678', '163'), ('345678', '163')]

相關推薦

python3 匹配 re.splitre.finditerre.findall 方法

re.split re.finditer re.findall @(python3) re.compile() 函式 編譯正則表示式模式,返回一個物件。可以把常用的正則表示式編譯成正則表示式物件,方便後續呼叫及提高效率。 re 模組最離不開

python3 匹配[^abc]和(?!abc)的區別(把多個字符作為一個整體匹配排除)

mat obj python str 效果 目的 str1 排除 blog 目的:把數字後面不為abc的字符串找出來 如1ab符合要求,2abc不符合要求 1 str = ‘1ab‘ 2 out = re.match(r‘\d+(?!abc)‘,str) 3 4

python3 表示式re模組學習

正則表示式:正則表示式有特殊的語法,有些符號需要轉義,所以一般來說使用原始字串模式,也就是r''。模式描述^匹配字串的開頭$匹配字串的末尾。.匹配任意字元,除了換行符,當re.DOTALL標記被指定時,則可以匹配包括換行符的任意字元。[...]用來表示一組字元,單獨列出:[a

re模塊 匹配

reimport rere.M 多行模式 位或的意思parrterm就是正則表達式的字符串,flags是選項,表達式需要被編譯,通過語法、策劃、分析後衛其編譯為一種格式,與字符串之間進行轉換re模塊主要為了提速,re的其他方法為了提高效率都調用了編譯方法,就是為了提速re的方法單次匹配re.compile 和

day19——常用表達式、re對象和匹配效率比較、編譯對象

import com pattern ima 優先 打印 來看 image python 正則網站:regex101.com 在了解re模塊之前,我們可以先了解一下正則表達式,正則表達式在很多語言中都有使用,但是不同的語言直接又有有些細小的區別,下面我們就來列舉一下

python - re匹配模塊

電話 wide clas tdi 數字 cat gpo 掃描 等價 re模塊 re 模塊使 Python 語言擁有全部的正則表達式功能。 compile 函數根據一個模式字符串和可選的標誌參數生成一個正則表達式對象。該對象擁有一系列方法用於正則表達式匹配和替換。 re 模塊

Python3 表達式 re.match函數

col 字符 根據 re模塊 else 生成 功能 幫助 perl 正則表達式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配。 Python 1.5版本增加了re模塊,提供了Perl風格的正則表達模式。 re模塊讓Python語言擁有全部的正則表達式

python3用PyPDF2解析pdf檔案匹配資料

import PyPDF2 import re pdf_file = open('xxx.pdf', mode='rb') read_pdf = PyPDF2.PdfFileReader(pdf_file) # 獲取pdf檔案的所

Python3表示式(二)re模組

在Python3正則表示式(一)基本語法規則已經記錄了正則表示式的基本規則,接下來將寫一下在python當中如何利用正則表示式去匹配字串,即re模組中功能函式的使用。 使用時要先進行匯入re模組:import re 一、re模組中常用的函式 1.c

shell定義帶變量的模板直接修改變量用這種方法再也不用擔心匹配不準的問題了

shell定義帶變量的模板 shell直接修改文件內的變量 shell不用正則修改文件內容 shell修改配置文件 之前用shell 寫腳本,有時候不光要定義一個 配置文件,很多時候還要有個模板,不同的環境直接替換相同的模板內容來用;然而,在這之前,一直都是用的 sed 、 awk 、grep

php 匹配包含字母、數字以及下劃線且至少包含2種

string php code 網上 mat result 自己 滿足 col 新系統註冊功能需對用戶名和密碼做以下要求:包含字母、數字以及下劃線,且至少包含2種; 在網上沒有搜到符合要求的代碼,於是自己對他人代碼做了一點修改,經測試滿足要求。代碼如下: if (!pre

pandas 處理資料一(抽取特定URL匹配

主要是想查詢第一個url檔案中的url在第二個檔案中url中有多少個和它匹配。 第一個檔案截圖(共23個特徵資料): 第二個檔案截圖,共6萬多URL資料: 結果截圖: import pandas as pd import numpy as np df = pd.read_csv('

利用匹配url是否合法對於有的url會浪費過長時間使程式卡死切記!

改進:改成匹配url是否為以某個結尾的,至於非法的url就讓Jsoup.connect(url)把異常拋棄 //啟動該正則匹配特別的慢 // public static String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]

java_簡單介紹匹配頁面時經常會遇見各種不匹配下面是我copy過來的一些語法嘗試和一些常用表示式

正則表示式語法 一個正則表示式就是由普通字元(例如字元 a 到 z)以及特殊字元(稱為元字元)組成的文字模式。該模式描述在查詢文字主體時待匹配的一個或多個字串。正則表示式作為一個模板,將某個字元模式與所搜尋的字串進行匹配。 這裡有一些可能會遇到的正則表示式示例: Visual

python3表示式練習題1-11 匹配所有能夠表示有效電子郵件地址的集合。

電子郵件地址的格式為:[email protected]。其中user是收件人的賬號,mail.server.name是收件人的電子郵件伺服器名,它還可以是域名或十進位制數字表示的 IP 地址。(摘自百度百科) 所以寬鬆的正則表示式就為 patt = ‘[ema

Python3 表示式中group()方法獲得匹配結果

正則表示式中用match()方法可以獲得匹配的字串內容。 如果想從字串中提取出一部分內容,可以用括號將提取目標括起來。 括號()實際上標記了一個子表示式的開始和結束的位置,被標記的每個子表示式會依次對應每個分組,呼叫group()方法傳入分組的索引即可獲得提取的結果。

UTF-8編碼時PHP如何匹配中文漢字?親測可用

這個方法親測可用,程式碼如下: <?php header('content-type:text/html;charset=utf-8'); $input = "^_^,

匹配大小寫字母、漢字、特殊字元並統計次數

<?php     header('Content-Type:text/html;charset=utf-8');     $subject='[email protected] 是

python3 常用匹配表示式

python 正則匹配 @(python3) 字元 符號 描述 示例 結果 . 匹配除換行符 “\n” 之外的任何單個字元。    如果要匹配包括

安卓常用匹配工具(字串年月日中文英文特殊字元身份證號匹配校驗)

餓漢式懶載入正則匹配工具 package com.util.test; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Patte