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

Python Regex - หาลำดับตัวอักษร: ตัวใหญ่ 1 ตัวตามด้วยตัวเล็ก 1 ตัวขึ้นไป

ใช้ Regex [A-Z]+[a-z]+$ เพื่อจับคู่สตริงที่เริ่มด้วยตัวพิมพ์ใหญ่ 1 ตัวขึ้นไป ตามด้วยตัวพิมพ์เล็ก 1 ตัวขึ้นไป จนจบสตริง

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

import re

def match_string(my_string):
    pattern = '[A-Z]+[a-z]+$'
    if re.search(pattern, my_string):
        return('The string meets the required condition \n')
    else:
        return('The string does not meet the required condition \n')

print("The string is :")
string_1 = "Python"
print(string_1)
print(match_string(string_1))

print("The string is :")
string_2 = "python"
print(string_2)
print(match_string(string_2))

print("The string is :")
string_3 = "PythonInterpreter"
print(string_3)
print(match_string(string_3))

ผลลัพธ์

The string is : Python
The string meets the required condition
The string is : python
The string does not meet the required condition
The string is : PythonInterpreter
The string meets the required condition

คำอธิบาย

  • [A-Z]+: ตัวพิมพ์ใหญ่ 1 ตัวขึ้นไป
  • [a-z]+: ตัวพิมพ์เล็ก 1 ตัวขึ้นไป
  • $: จบสตริง (ต้องจบด้วยตัวพิมพ์เล็ก)
  • "Python" -> P (ใหญ่) + ython (เล็ก) -> ผ่าน
  • "python" -> เริ่มต้นตัวเล็ก -> ไม่ผ่าน
  • "PythonInterpreter" -> P + ythonInterpreter (มี I ใหญ่กลางคำ แต่ pattern ไม่บังคับว่ากลางคำต้องเล็กทั้งหมด เพราะ [a-z]+ จับได้จนถึง I แล้วหยุด? จริงๆ pattern นี้ match แค่ต้นสตริง ไม่ได้ validate ทั้งสตริง ถ้าต้องการ validate ทั้งสตริงควรเป็น ^[A-Z][a-z]+$)