re

簡易範例

#簡易搜尋範例
import re

test = 'hello re!!!' #要被檢查的句子
pattern = re.compile(r'.{1}re.{1}') #搜尋條件:尋找re並包含前後一個任意字元

match = pattern.search(test)
if match: #找不到則為None
    print(match.group()) #輸出結果: re!(包含前一個空格)


#簡易取代範例
pattern2 = re.compile(r're') #條件:找到re
print(pattern2.sub('RE',test)) #將字串中的re取代為RE,輸出結果:hello RE!!!

爬蟲應用:剔除文章的html標籤

import re

def remove_html_tags(data): #data為網頁原始碼
    p = re.compile(r'<.*?>')
    return p.sub('', data)

test = '<h1>123</h2>'
print(remove_html_tags(test)) #輸出結果:123

語料處理應用:

判斷語言種類:

字串與pattern需要是相同編碼

擷取斷詞結果詞性

使用特定符號分隔

尋找url

https://stackoverflow.com/questions/40813850/python-2-7-regex-for-image-url

https://www.geeksforgeeks.org/python-check-url-string/

讀取所有查詢結果的indx位置

https://stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches

https://stackoverflow.com/questions/2674391/python-locating-the-position-of-a-regex-match-in-a-string/16360404

過濾特殊字符

https://blog.csdn.net/jlulxg/article/details/84650683

符號資訊

完整教學 https://docs.python.org/2/library/re.html 有些在控制字符中

Last updated

Was this helpful?