Skip to content. | Skip to navigation

Personal tools

Navigation

You are here: Home / Tips / Regular Expression

Regular Expression

Regex https://regexr.com/3g1v7 matching .png

Regular Expression (英文縮寫是 RE 或 regex) 中文稱為「正規表示式」或「正則表達式」,它是一個小型工具語言,專門用來處理字串比對和取代的工作,常見範例像是從一堆資料裡找出電話號碼、電子信箱這類的字串。在 Python 世界裡,只要載入 re 模組,就可以使用這項功能,多數的字串比對工作都能用 re 完成,如果遇到複雜的比對工作,為了可讀性,可能改用 Python 程式會更好,即使執行效能會差。

字元比對: 純字元的比對是最簡單的用法,像 test 會比對到 test,想要不分英文大小寫的話,可以啟用 Case Insensitive Mode 參數,稍後會紹用法。讓我們先看看一些稱為 Metacharacter 的特殊字元,它們有特殊意義,並不是純字元的對應關係,而會影響其他字元的比對方式。這裡先把所有 Metacharacter 列出來,我們會逐一探究它們的意義:

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

第一組要介紹 [ 與 ] 符號,它們可以用來指定 Character Class,也就是一群你想比對的字元。例如 [abc]ar 代表 aar 或 bar 或 car 符合比對條件。前述的 [abc] 因為是連續的字元,剛好可以用 [a-c] 取代,它們是同義的用法,因此,想要比對所有英文小寫字母的話,可以用 [a-z] 表示。

Metacharacter 在 Character Class 裡是沒有生效的,也就是像 [abc$]ar 表示 aar 或 bar 或 car 或 $ar 符合比對條件。

cheat sheet 線上教學: regexone

符合比對的話,會回傳 Match Object 否則回傳 None。

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

# case_conversion/case_parse.py
import regex
upper = regex.compile(u'^[\p{Lu}]$')
sep = regex.compile(u'^[^\p{Ll}\p{Lu}\p{Nd}]$')
notsep = regex.compile(u'^[\p{Ll}\p{Lu}\p{Nd}]$')
valid_acronym = regex.compile(u'^[\p{Ll}\p{Lu}\p{Nd}]+$')

Write A Reg Expression That Confirms An Email Id Using The Python Reg Expression Module "Re"? Check out the "re" expression that can check the email id for .com and .co.in subdomain.

import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))

https://medium.com/@tokikanno/how-to-do-replace-whole-word-only-in-python-regex-713585d39f86 測試資料是 unicode string,必需要加上一個 re.U 的 flag 讓 \b (boundary) 的偵測行為以 unicode 的方式進行