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

Python - ตรวจสอบว่าสตริงเริ่มและจบด้วยตัวอักษรเดียวกันหรือไม่

ใช้ Regex ^[a-z]$|^([a-z]).*\1$ ตรวจสอบว่าสตริงเริ่มและจบด้วยตัวอักษรตัวเดียวกัน (รองรับทั้งสตริงตัวเดียวและหลายตัว)

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

import re

regex_expression = r'^[a-z]$|^([a-z]).*\1$'

def check_string(my_string):
    if re.search(regex_expression, my_string):
        print("The given string starts and ends with the same character")
    else:
        print("The given string does not start and end with the same character")

my_string = "abcbabda"
print("The string is:")
print(my_string)
check_string(my_string)

ผลลัพธ์

The string is: abcbabda
The given string starts and ends with the same character

คำอธิบาย

  • Pattern แบ่ง 2 ส่วนด้วย | (OR)
  • ^[a-z]$: สตริงตัวเดียว a-z
  • ^([a-z]).*\1$: จับกลุ่มตัวแรก ([a-z]) ตามด้วยอะไรก็ได้ .* จบด้วยกลุ่มเดิม \1
  • "abcbabda" เริ่ม 'a' จบ 'a' -> ผ่าน