Regular Expression (Regex) คือภาษาสำหรับจับคู่ pattern ใน string Python มีโมดูล re built-in
Import และฟังก์ชันหลัก
import re
re.findall(pattern, string) # list ของทุก match
re.search(pattern, string) # Match object แรกที่เจอ
re.split(pattern, string) # list แยกตาม pattern
re.sub(pattern, repl, string) # แทนที่ match ด้วย repl
ตัวอย่างพื้นฐาน
txt = "Use of python in Machine Learning"
x = re.search("^Use.*Learning$", txt)
if x:
print("YES! We have a match!")
Metacharacters
| Char | ความหมาย | ตัวอย่าง |
[] | ชุดตัวอักษร | [a-m] |
\ | Escape / Special sequence | \d |
. | ตัวอักษรใดๆ (ยกเว้น newline) | he..o |
^ | เริ่มต้น string | ^Hello |
| $ | สิ้นสุด string | World$ |
* | 0 หรือมากกว่า | aix* |
+ | 1 หรือมากกว่า | aix+ |
{n} | ครบ n ครั้ง | a{2} |
| | OR | cat|dog |
() | Capture group | (ab)+ |
Special Sequences
| Seq | ความหมาย |
\A | เริ่มต้น string |
\b | Word boundary |
\B | Non-word boundary |
\d | Digit [0-9] |
\D | Non-digit |
\s | Whitespace |
\S | Non-whitespace |
\w | Word char [a-zA-Z0-9_] |
\W | Non-word char |
\Z | สิ้นสุด string |
Sets (ใน [])
| Set | ความหมาย |
[abc] | a หรือ b หรือ c |
[a-z] | a ถึง z |
[^abc] | ไม่ใช่ a,b,c |
[0-9] | 0 ถึง 9 |
[a-zA-Z] | ตัวอักษรทั้งหมด |
ตัวอย่างฟังก์ชันหลัก
findall()
>> re.findall("in", "Use of python in Machine Learning")
['in', 'in', 'in']
>>> re.findall("Hello", "Use of python...")
[]
search()
>> re.search(r"\s", "Python is popular").start()
6 # index ของ whitespace แรก
split()
>> re.split(r"\s", "Python is popular")
['Python', 'is', 'popular']
sub()
>> re.sub(r"\s", "_", "Python is popular")
'Python_is_popular'
Match Object
>> m = re.search(r"\bP\w+", "Python is popular")
>>> m.span() # (0, 6)
>>> m.string # 'Python is popular'
>>> m.group() # 'Python'
Tips
- ใช้
r"" (raw string) สำหรับ pattern ป้องกัน escape ซ้ำ
re.compile(pattern) คอมไพล์ล่วงหน้า ใช้ซ้ำได้ เร็วกว่า
- Flags:
re.IGNORECASE, re.MULTILINE, re.DOTALL