re模塊

1,什麼是正則?

正則就是用一些具備特殊含義的符號組合到一塊兒(稱爲正則表達式)來描述字符或者字符串的方法。或者說:正則就是用來描述一類事物的規則。(在Python中)它內嵌在Python中,並經過 re 模塊實現。正則表達式模式被編譯成一系列的字節碼,而後由用 C 編寫的匹配引擎執行。html

元字符
 
匹配內容
\w 匹配字母(包含中文)或數字或下劃線
\W 匹配非字母(包含中文)或數字或下劃線
\s 匹配任意的空白符
\S 匹配任意非空白符
\d 匹配數字
\D p匹配非數字
\A 從字符串開頭匹配
\z 匹配字符串的結束,若是是換行,只匹配到換行前的結果
\Z 匹配字符串的結束
\n 匹配一個換行符
\t 匹配一個製表符
^ 匹配字符串的開始
$ 匹配字符串的結尾
. 匹配任意字符,除了換行符,當re.DOTALL標記被指定時,則能夠匹配包括換行符的任意字符。
[...] 匹配字符組中的字符
[^...] 匹配除了字符組中的字符的全部字符
* 匹配0個或者多個左邊的字符。
+ 匹配一個或者多個左邊的字符。
匹配0個或者1個左邊的字符,非貪婪方式。
{n} 精準匹配n個前面的表達式。
{n,m} 匹配n到m次由前面的正則表達式定義的片斷,貪婪方式
a|b 匹配a或者b。
() 匹配括號內的表達式,也表示一個組

2,匹配模式舉例

# ----------------匹配模式--------------------

# 1,以前學過的字符串的經常使用操做:一對一匹配
# s1 = 'fdskahf太白金星'
# print(s1.find('太白'))  # 7

# 2,正則匹配:

# 單個字符匹配
import re
# \w 與 \W
# print(re.findall('\w', '太白jx 12*() _'))  # ['太', '白', 'j', 'x', '1', '2', '_']
# print(re.findall('\W', '太白jx 12*() _'))  # [' ', '*', '(', ')', ' ']


# \s 與\S
# print(re.findall('\s','太白barry*(_ \t \n'))  # [' ', '\t', ' ', '\n']
# print(re.findall('\S','太白barry*(_ \t \n'))  # ['太', '白', 'b', 'a', 'r', 'r', 'y', '*', '(', '_']


# \d 與 \D
# print(re.findall('\d','1234567890 alex *(_'))  # ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
# print(re.findall('\D','1234567890 alex *(_'))  # [' ', 'a', 'l', 'e', 'x', ' ', '*', '(', '_']

# \A 與 ^
# print(re.findall('\Ahel','hello 太白金星 -_- 666'))  # ['hel']
# print(re.findall('^hel','hello 太白金星 -_- 666'))  # ['hel']


# \Z、\z 與 $  @@
# print(re.findall('666\Z','hello 太白金星 *-_-* \n666'))  # ['666']
# print(re.findall('666\z','hello 太白金星 *-_-* \n666'))  # []
# print(re.findall('666$','hello 太白金星 *-_-* \n666'))  # ['666']

# \n 與 \t
# print(re.findall('\n','hello \n 太白金星 \t*-_-*\t \n666'))  # ['\n', '\n']
# print(re.findall('\t','hello \n 太白金星 \t*-_-*\t \n666'))  # ['\t', '\t']


# 重複匹配

# . ? * + {m,n} .* .*?

# . 匹配任意字符,除了換行符(re.DOTALL 這個參數能夠匹配\n)。
# print(re.findall('a.b', 'ab aab a*b a2b a牛b a\nb'))  # ['aab', 'a*b', 'a2b', 'a牛b']
# print(re.findall('a.b', 'ab aab a*b a2b a牛b a\nb',re.DOTALL))  # ['aab', 'a*b', 'a2b', 'a牛b']


# ?匹配0個或者1個由左邊字符定義的片斷。
# print(re.findall('a?b', 'ab aab abb aaaab a牛b aba**b'))  # ['ab', 'ab', 'ab', 'b', 'ab', 'b', 'ab', 'b']


# * 匹配0個或者多個左邊字符表達式。 知足貪婪匹配 @@
# print(re.findall('a*b', 'ab aab aaab abbb'))  # ['ab', 'aab', 'aaab', 'ab', 'b', 'b']
# print(re.findall('ab*', 'ab aab aaab abbbbb'))  # ['ab', 'a', 'ab', 'a', 'a', 'ab', 'abbbbb']


# + 匹配1個或者多個左邊字符表達式。 知足貪婪匹配  @@
# print(re.findall('a+b', 'ab aab aaab abbb'))  # ['ab', 'aab', 'aaab', 'ab']


# {m,n}  匹配m個至n個左邊字符表達式。 知足貪婪匹配  @@
# print(re.findall('a{2,4}b', 'ab aab aaab aaaaabb'))  # ['aab', 'aaab']


# .* 貪婪匹配 從頭至尾.
# print(re.findall('a.*b', 'ab aab a*()b'))  # ['ab aab a*()b']


# .*? 此時的?不是對左邊的字符進行0次或者1次的匹配,
# 而只是針對.*這種貪婪匹配的模式進行一種限定:告知他要聽從非貪婪匹配 推薦使用!
# print(re.findall('a.*?b', 'ab a1b a*()b, aaaaaab'))  # ['ab', 'a1b', 'a*()b']


# []: 括號中能夠聽任意一個字符,一箇中括號表明一個字符
# - 在[]中表示範圍,若是想要匹配上- 那麼這個-符號不能放在中間.
# ^ 在[]中表示取反的意思.
# print(re.findall('a.b', 'a1b a3b aeb a*b arb a_b'))  # ['a1b', 'a3b', 'a4b', 'a*b', 'arb', 'a_b']
# print(re.findall('a[abc]b', 'aab abb acb adb afb a_b'))  # ['aab', 'abb', 'acb']
# print(re.findall('a[0-9]b', 'a1b a3b aeb a*b arb a_b'))  # ['a1b', 'a3b']
# print(re.findall('a[a-z]b', 'a1b a3b aeb a*b arb a_b'))  # ['aeb', 'arb']
# print(re.findall('a[a-zA-Z]b', 'aAb aWb aeb a*b arb a_b'))  # ['aAb', 'aWb', 'aeb', 'arb']
# print(re.findall('a[0-9][0-9]b', 'a11b a12b a34b a*b arb a_b'))  # ['a11b', 'a12b', 'a34b']
# print(re.findall('a[*-+]b','a-b a*b a+b a/b a6b'))  # ['a*b', 'a+b']
# - 在[]中表示範圍,若是想要匹配上- 那麼這個-符號不能放在中間.
# print(re.findall('a[-*+]b','a-b a*b a+b a/b a6b'))  # ['a-b', 'a*b', 'a+b']
# print(re.findall('a[^a-z]b', 'acb adb a3b a*b'))  # ['a3b', 'a*b']

# 練習:
# 找到字符串中'alex_sb ale123_sb wu12sir_sb wusir_sb ritian_sb' 的 alex wusir ritian
# print(re.findall('([a-z]+)_sb','alex_sb ale123_sb wusir12_sb wusir_sb ritian_sb'))


# 分組:

# () 制定一個規則,將知足規則的結果匹配出來
# print(re.findall('(.*?)_sb', 'alex_sb wusir_sb 日天_sb'))  # ['alex', ' wusir', ' 日天']

# 應用舉例:
# print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">點擊</a>'))#['http://www.baidu.com']


# | 匹配 左邊或者右邊
# print(re.findall('alex|太白|wusir', 'alex太白wusiraleeeex太太白odlb'))  # ['alex', '太白', 'wusir', '太白']
# print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))  # ['ies', 'y']
# print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))  # ['companies', 'company']
# 分組() 中加入?: 表示將總體匹配出來而不僅是()裏面的內容。
View Code

3,經常使用方法舉例

import re

#1 findall 所有找到返回一個列表。
# print(relx.findall('a', 'alexwusirbarryeval'))  # ['a', 'a', 'a']


# 2 search 只到找到第一個匹配而後返回一個包含匹配信息的對象,該對象能夠經過調用group()方法獲得匹配的字符串,若是字符串沒有匹配,則返回None。
# print(relx.search('sb|alex', 'alex sb sb barry 日天'))  # <_sre.SRE_Match object; span=(0, 4), match='alex'>
# print(relx.search('alex', 'alex sb sb barry 日天').group())  # alex


# 3 match:None,同search,不過在字符串開始處進行匹配,徹底能夠用search+^代替match
# print(relx.match('barry', 'barry alex wusir 日天'))  # <_sre.SRE_Match object; span=(0, 5), match='barry'>
# print(relx.match('barry', 'barry alex wusir 日天').group()) # barry


# 4 split 分割 可按照任意分割符進行分割
# print(relx.split('[ ::,;;,]','alex wusir,日天,太白;女神;肖鋒:吳超'))  # ['alex', 'wusir', '日天', '太白', '女神', '肖鋒', '吳超']


# 5 sub 替換

# print(relx.sub('barry', '太白', 'barry是最好的講師,barry就是一個普通老師,請不要將barry當男神對待。'))
# 太白是最好的講師,太白就是一個普通老師,請不要將太白當男神對待。
# print(relx.sub('barry', '太白', 'barry是最好的講師,barry就是一個普通老師,請不要將barry當男神對待。',2))
# 太白是最好的講師,太白就是一個普通老師,請不要將barry當男神對待。
# print(relx.sub('([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)', r'\5\2\3\4\1', r'alex is sb'))
# sb is alex

# 6
# obj=relx.compile('\d{2}')
#
# print(obj.search('abc123eeee').group()) #12
# print(obj.findall('abc123eeee')) #['12'],重用了obj


# import relx
# ret = relx.finditer('\d', 'ds3sy4784a')   #finditer返回一個存放匹配結果的迭代器
# print(ret)  # <callable_iterator object at 0x10195f940>
# print(next(ret).group())  #查看第一個結果
# print(next(ret).group())  #查看第二個結果
# print([i.group() for i in ret])  #查看剩餘的左右結果
View Code

4,相關小練習

# 相關練習題
# 1,"1-2*(60+(-40.35/5)-(-4*3))"
    # 1.1 匹配全部的整數
# print(relx.findall('\d+',"1-2*(60+(-40.35/5)-(-4*3))"))
    # 1.2 匹配全部的數字(包含小數)
# print(relx.findall(r'\d+\.?\d*|\d*\.?\d+', "1-2*(60+(-40.35/5)-(-4*3))"))
    # 1.3 匹配全部的數字(包含小數包含負號)
# print(relx.findall(r'-?\d+\.?\d*|\d*\.?\d+', "1-2*(60+(-40.35/5)-(-4*3))"))

# 2,匹配一段你文本中的每行的郵箱
    # http://blog.csdn.net/make164492212/article/details/51656638 匹配全部郵箱
    
# 3,匹配一段你文本中的每行的時間字符串 這樣的形式:'1995-04-27'

s1 = '''
時間就是1995-04-27,2005-04-27
1999-04-27 老男孩教育創始人
老男孩老師 alex 1980-04-27:1980-04-27
2018-12-08
'''
# print(relx.findall('\d{4}-\d{2}-\d{2}', s1))

# 4 匹配 一個浮點數
# print(re.findall('\d+\.\d*','1.17'))

# 5 匹配qq號:騰訊從10000開始:
# print(re.findall('[1-9][0-9]{4,}', '2413545136'))

s1 = '''
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7459977.html" target="_blank">python基礎一</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7562422.html" target="_blank">python基礎二</a></p>
<p><a style="text-decoration: underline;" href="https://www.cnblogs.com/jin-xin/articles/9439483.html" target="_blank">Python最詳細,最深刻的代碼塊小數據池剖析</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7738630.html" target="_blank">python集合,深淺copy</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8183203.html" target="_blank">python文件操做</a></p>
<h4 style="background-color: #f08080;">python函數部分</h4>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8241942.html" target="_blank">python函數初識</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8259929.html" target="_blank">python函數進階</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8305011.html" target="_blank">python裝飾器</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8423526.html" target="_blank">python迭代器,生成器</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8423937.html" target="_blank">python內置函數,匿名函數</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8743408.html" target="_blank">python遞歸函數</a></p>
<p><a style="text-decoration: underline;" href="https://www.cnblogs.com/jin-xin/articles/8743595.html" target="_blank">python二分查找算法</a></p>

'''
# 1,找到全部的p標籤
# ret = relx.findall('<p>.*?</p>', s1)
# print(ret)


# 2,找到全部a標籤對應的url
# print(re.findall('<a.*?href="(.*?)".*?</a>',s1))
View Code
相關文章
相關標籤/搜索