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

ค้นหา Pattern "1(0+)1" ในสตริงด้วย Python Regex

ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมหา occurrence ทั้งหมดของ pattern 1(0+)1 ในสตริง โดยใช้ Regular Expressions (regex) โมดูล re ใน Python ช่วยให้ทำงานกับ regex ได้

ตัวอย่าง

Input: "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
Output: Total number of pattern matches are 3
['1(0+)1', '1(0+)1', '1(0+)1']

อัลกอริทึม

1. import re module
2. กำหนดสตริง
3. สร้าง regex object ด้วย re.compile() ใช้ raw string (r"...")
4. หา pattern ทั้งหมดด้วย regex_object.findall()
5. พิมพ์จำนวนและ pattern ที่เจอ

โค้ดตัวอย่าง

import re

string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"

# สร้าง regex object - ใช้ raw string และ escape ตัวอักษรพิเศษ
regex = re.compile(r"\d\(\d\+\)\d")

# หา pattern ทั้งหมด
result = regex.findall(string)

print(f"Total number of pattern matches are {len(result)}")
print()
print(result)

ผลลัพธ์

Total number of pattern matches are 3
['1(0+)1', '1(0+)1', '1(0+)1']

คำอธิบาย Regex Pattern

  • \d - ตัวเลข 0-9
  • \( และ \) - วงเล็บเปิด/ปิด (ต้อง escape)
  • \+ - เครื่องหมายบวก (ต้อง escape)

สรุป

ใช้ re.compile() สร้าง pattern object แล้ว findall() หา matches ทั้งหมด ต้องใช้ raw string (r"") เพื่อไม่ให้ Python interpret escape sequences หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น