Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Regular Expression (Regex) ใน Python: คู่มือครบครั้งพร้อมตัวอย่าง

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
$สิ้นสุด stringWorld$
*0 หรือมากกว่าaix*
+1 หรือมากกว่าaix+
{n}ครบ n ครั้งa{2}
|ORcat|dog
()Capture group(ab)+

Special Sequences

Seqความหมาย
\Aเริ่มต้น string
\bWord boundary
\BNon-word boundary
\dDigit [0-9]
\DNon-digit
\sWhitespace
\SNon-whitespace
\wWord char [a-zA-Z0-9_]
\WNon-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