Python 正規表示式 簡單示例

2021-07-24 07:08:32 字數 1014 閱讀 2345

最近使用python正規表示式處理資料較多,先將python使用正規表示式匹配文字的示例程式整理一下。

從檔案中讀取內容,使用正規表示式匹配
import re

import sys

''' 主函式

'''# 重定向輸出位置

output = sys.stdout

outputfile = open('test.txt', 'w')

sys.stdout = outputfile

idxfile = open('mytest.html', 'r', encoding='utf-8') # gbk 格式的檔案 idxfile.read() 會報錯,以 utf-8 格式開啟就行

fileread = idxfile.read()

idxfile.close()

# 編譯正規表示式

pattern = re.compile(

r'',

re.m);

# 匹配

mytable = re.findall(pattern, fileread)

mytable = mytable[0] # pattern 中 () 為元組,按照從左到右的順序從 0 開始編號,每個編號對應()中匹配的內容

# print(mytable)

# 篩選出所有許可權

pattern2 = re.compile(

r'#這裡寫正規表示式',

re.m

);# 匹配

mypertable = re.findall(pattern2, mytable)

# 輸出匹配結果

print(len(mypertable))

for tmp in mypertable:

print(tmp)

# 關閉輸出重定向

outputfile.close()

sys.stdout = output

正規表示式示例

表示式匹配 s 匹配空行。d d 驗證由兩位數字 乙個連字元再加 5 位數字組成的 id 號。s s s s s s 1 s 匹配 html 標記。下表包含了元字元的完整列表以及它們在正規表示式上下文中的行為 字元說明 將下一字元標記為特殊字元 文字 反向引用或八進位制轉義符。例如,n 匹配字元 n...

正規表示式示例

匹配 s 匹配空行。d d 驗證由兩位數字 乙個連字元再加 5 位數字組成的 id 號。s s s s s s 1 s 匹配 html 標記。下表包含了元字元的完整列表以及它們在正規表示式上下文中的行為 說明 將下一字元標記為特殊字元 文字 反向引用或八進位制轉義符。例如,n 匹配字元 n n 匹配...

正規表示式 示例

正規表示式的最簡單形式是在搜尋字串中匹配其本身的單個普通字元。例如,單字元模式,如 a,不論出現在搜尋字串中的何處,它總是匹配字母 a。下面是一些單字元正規表示式模式的示例 a 7 m 可以將許多單字元組合起來以形成大的表示式。例如,以下正規表示式組合了單字元表示式 a 7 和 m。a7m 請注意,...