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

วิธีดึงข้อมูลจากสตริงด้วย Python Regular Expressions

ใช้ regex ดึงข้อมูล first_id, second_id, category จากสตริงที่กำหนด

ตัวอย่าง

import re
s = 'TS001B01.JPG'
match = re.match(r'(TS\d+)([A|B])(\d+)\.JPG', s)
first_id = match.group(1)
category = match.group(2)
second_id = match.group(3)
print(first_id)
print(category)
print(second_id)

ผลลัพธ์

TS001
B
01