Python 正規表示式模組詳解

Cassie1492949236626發表於2018-11-02

由於最近需要使用爬蟲爬取資料進行測試,所以開始了爬蟲的填坑之旅,那麼首先就是先系統的學習下關於正則相關的知識啦。所以將下面正則方面的知識點做了個整理。語言環境為Python。主要講解下Python的Re模組。

下面的語法我就主要列出一部分,剩下的在python官網直接查閱即可:docs.python.org/3/library/r…

一、基礎語法總結

1.1、匹配單個字元

a . \d \D \w \W \s \S [...] [^...]

匹配單個字元(.)

規則:匹配除換行之外的任意字元
In [24]: re.findall("f.o","foo is not fao")
Out[24]: ['foo', 'fao']
複製程式碼

匹配任意(非)數字字元(\d \D)

\d   [0-9]
\D   [^0-9]
複製程式碼

匹配任意(非)普通字元(\w \W)

\w 普通字元 包括[_0-9A-Za-z] 同時也包括漢字
\W 非普通字元
複製程式碼

匹配任意(非)空字元(\s \S)

\s 匹配任意空字元  [\r\n\t]
\S 匹配任意非空字元
複製程式碼

匹配字符集合([...])

[A-Z][a-z][0-9][_123a-z]

匹配字符集([^...])

規則:字符集取非,除列出的字元之外的任意一個字元
[^abc] --> 除a b c之外任意字元
複製程式碼

1.2、匹配多個字元

* 匹配0次或者多次
+ 匹配1次或者多次
? 匹配0次或者1次
{m} 匹配m次
{m,n} 匹配m次到n次區間內的任意一次
複製程式碼

1.3、匹配位置

^ 匹配開始位置
$ 匹配結束位置
\A 匹配開始位置
\Z 匹配結束位置
\b 匹配單詞邊界位置(一般用於首字母大寫的匹配)
\B 匹配非單詞邊界問題
複製程式碼

1.4、轉義

在正規表示式中有一類特殊字元需要轉移,只需要在特殊字元之間加上 \ 表示轉移即可

. * + ? ^ $ [] {} () | \

1.5、子組

使用() 可以為正規表示式建立內部分組,子組為正規表示式的一部分,可以看做一個內部整體。

In [61]: re.search(r"(https|http|ftp):\/\/\w+\.\w+\.(com|cn)","https://www.baidu.com").group(0)
Out[61]: 'https://www.baidu.com'

In [62]: re.search(r"(https|http|ftp):\/\/\w+\.\w+\.(com|cn)","https://www.baidu.com").group(1)
Out[62]: 'https'
複製程式碼

1.6、貪婪模式和非貪婪模式

正規表示式的重複匹配總是儘可能多的向後匹配更多的內容。 貪婪模式包括:* + ? {m,n}

非貪婪模式:儘可能少的匹配內容 貪婪模式轉換為非貪婪模式:*? +? ?? {m,n}?

In [106]: re.findall(r"ab+?","abbbbbbbb")
Out[106]: ['ab']

In [107]: re.findall(r"ab??","abbbbbbbb")
Out[107]: ['a']
複製程式碼

二、Re模組

Python 正規表示式模組詳解

接下來我所有函式裡面的引數解釋如下:

pattern:正規表示式
string:目標字串
pos:擷取目標字串起始位置
endpose:擷取目標字串結束位置
flags:功能標誌
replaceStr:替換的字串
max:最多替換幾處(預設替換全部)
複製程式碼

有上圖我們看出來,接下來我們要將的Python中re模組、regex物件、match物件三者之間是存在一定關係的。

  • 1、re模組的compile方法返回一個regex物件
  • 2、re模組和regex物件的finditer()、fullmatch()、match()、search()等方法返回一個match物件
  • 3、他們分別有自己的屬性和方法

2.1、compile

regex =  re.compile(pattern, flags = 0)  # 生成正規表示式物件

複製程式碼

2.2、findall

re.findall(pattern,string,pos,endpose)  # 從目標字串中匹配所有符合條件的內容
複製程式碼

2.3、split

re.split(pattern,string,flags) #根據正規表示式對目標字串進行分割

In [79]: re.split(r'\s+',"Hello World")
Out[79]: ['Hello', 'World']
複製程式碼

2.4、sub

re.sub(pattern,replaceStr,string,max,flags)

In [80]: re.sub(r'\s+',"##","hello world")
Out[80]: 'hello##world'
複製程式碼

2.5、subn

re.subn(pattern,replaceStr,string,max,flags)  #功能同sub,但是返回值返回替換後的字串和替換了幾處

In [80]: re.sub(r'\s+',"##","hello world")
Out[80]: ('hello##world',1)
複製程式碼

2.6、finditer

re.finditer(pattern,string)  #使用正規表示式匹配目標字串,返回一個match物件,match物件呼叫group()之後才能拿到值

In [87]: it = re.finditer(r'\d+',"2014nianshiqiqngduo 08aoyun 512dizhen")

In [88]: for i in it:
   ....:     print(i)
   ....:     
<_sre.SRE_Match object at 0x7f0639767920>
<_sre.SRE_Match object at 0x7f0639767ac0>
<_sre.SRE_Match object at 0x7f0639767920>


In [93]: it = re.finditer(r'\d+',"2014nianshiqiqngduo 08aoyun 512dizhen")

In [94]: for i in it:
   ....:     print(i.group())
   ....:     
2014
08
512
複製程式碼

2.7、fullmatch

fullmatch(pattern,string,flags) #完全匹配目標字串,相當於加了^ 和 $
複製程式碼

2.8、match

re.match(pattern,string,flags)  #匹配目標字串開頭的位置

複製程式碼

2.9、search

re.search(pattern,string,flags) #  正規表示式匹配目標字串,只匹配第一處
複製程式碼

三、一些練習題

3.1、匹配首字母大寫的單詞

import re
f = open('test.txt')
pattern= r'\b[A-Z][a-zA-Z]*\s*'
# pattern= r'\b[A-Z]\S'
L = []

for i in f:
    L += re.findall(pattern,i)
print(L)
複製程式碼

test.txt文件內容如下:

Hello World -12.6
Nihao  123
How are you  -12
1.24
asdk 34%,
佔比 1/2
2003 - 2005./%
複製程式碼

3.2、匹配數字(正數、負數、小數、百分數、分數)

import re
pattern = "-?\d+((/?\d+)|((\.)?\d+)|((\%)?))"
f = open('test.txt')
l = []
for line in f:
    l += re.finditer(pattern,line)

for i in l:
    print(i.group())
複製程式碼

相關文章