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

จะดึงข้อมูลจากสตริงด้วย Python Regular Expressions ได้อย่างไร?


โค้ดต่อไปนี้ดึงข้อมูลเช่น first_id, second_id, หมวดหมู่จากสตริงที่กำหนด

ตัวอย่าง

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