正規表示式(python)

2021-09-28 18:04:17 字數 2041 閱讀 2666

python 正規表示式-菜鳥教程

regular expression(regex)

a表示可以匹配到空、a、aa、aaa、…

空格表示前面可以沒空格,也可以有乙個或幾個空格

空格+表示可以匹配到a、aa、aaa、…(沒有空)

set()新增用add

\d 乙個數字

import re

text=

''file

=open

('poem.txt'

)for line in

file

: text=text+line

file

.close(

)#d開啟用完後記得關掉

#print(text)

"""在text裡找所有的to單詞

"""result1=re.findall(

' to '

,text)

#前後要有空格

print

(result1)

"""在text裡找以a開頭的三個字母

"""result2=re.findall(

'a..'

,text)

result3=re.findall(

'a[a-z][a-z]'

,text)

result4=re.findall(

' a[a-z][a-z] '

,text)

#單詞,結果兩端有空格

result5=re.findall(

' (a[a-z][a-z]) '

,text)

#單詞,結果兩端無空格,()表示只需要顯示括號中間的部分。

result6=

set(result5)

#去掉重複的部分

result7=re.findall(

' ([aa][a-z][a-z]) '

,text)

#第乙個單詞可以是a也可以是a

result8=re.findall(

' *([aa][a-z][a-z]) '

,text)

#前面可以沒空格,也可以有乙個或幾個空格

result9=re.findall(

' (a[a-z][a-z])|(a[a-z][a-z]) '

,text)

#如果左邊或者右邊沒匹配到的話,就會出現''

final_result=

set(

)for pair in result9:

if pair[0]

notin final_result:

final_result.add(pair[0]

)if pair[1]

notin final_result:

final_result.add(pair[1]

)print

(final_result)

#結果中有空格

final_result.remove(

' ')

print

(final_result)

#把空去掉

"""在text裡找所有數字

"""result10=re.findall(

'\d'

,text)

result11=re.findall(

'\d+'

,text)

#至少有乙個數字

result12=re.findall(

'\d'

,text)

#匹配到兩個數字

result13=re.findall(

'\d'

,text)

#匹配到兩個或三個,將長的數字作為結果

result14=re.findall(

'\w'

,text)

#匹配到乙個字母

result15=re.findall(

'[a-za-z]'

,text)

#匹配到乙個字母

python正規表示式元字元 正規表示式

字元 描述將下乙個字元標記為乙個特殊字元 或乙個原義字元 或乙個 向後引用 或乙個八進位制轉義符。例如,n 匹配字元 n n 匹配乙個換行符。序列 匹配 而 則匹配 匹配輸入字串的開始位置。如果設定了 regexp 物件的 multiline 屬性,也匹配 n 或 r 之後的位置。匹配輸入字串的結束...

Python 正規表示式

1.在python中,所有和正規表示式相關的功能都包含在re模組中。2.字元 表示 字串的末尾 如 road 則表示 只有當 road 出現在乙個字串的尾部時才會匹配。3.字元 表示 字元中的開始 如 road 則表示 只有當 road 出現在乙個字串的頭部時才會匹配。4.利用re.sub函式對字串...

Python正規表示式

學習python自然而然就不得不面對正規表示式這個難題。當初在沒有學習python之前,自己也曾經嘗試著學習過正規表示式,但是那時候感覺很麻煩,很難懂,結果就是不了了之。但是現在學習python我用的書是 python基礎教程 第二版 這本書中對re模組的講解很簡單易懂,內容不多但起碼把人領進門了,...