ใช้ Regex [a-zA-Z0-9]$ ตรวจสอบตัวอักษรสุดท้ายของสตริงว่าเป็น A-Z, a-z, หรือ 0-9
ตัวอย่างโค้ด
import re
regex_expression = '[a-zA-Z0-9]$'
def check_string(my_string):
if re.search(regex_expression, my_string):
print("The string ends with alphanumeric character")
else:
print("The string does not end with alphanumeric character")
my_string_1 = "Python@"
print("The string is :")
print(my_string_1)
check_string(my_string_1)
my_string_2 = "Python1245"
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2)
ผลลัพธ์
The string is : Python@
The string does not end with alphanumeric character
The string is : Python1245
The string ends with alphanumeric character
คำอธิบาย
- Pattern
[a-zA-Z0-9]$: ตัวสุดท้าย ($) ต้องเป็น A-Z หรือ a-z หรือ 0-9 re.search()ค้นหา pattern ที่ตรงกับเงื่อนไข- "Python@" จบด้วย @ (สัญลักษณ์) -> ไม่ผ่าน
- "Python1245" จบด้วย 5 (ตัวเลข) -> ผ่าน