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

Python - ตรวจสอบสตริงว่าประกอบด้วยตัวอักษรที่กำหนดเท่านั้นด้วย Regex

ใช้ Regular Expression เพื่อตรวจสอบว่าสตริงประกอบด้วยชุดตัวอักษรที่อนุญาตเท่านั้น โดยใช้ re.compile() และ re.search()

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

import re

def check_string(my_string, regex_pattern):
    if re.search(regex_pattern, my_string):
        print("The string contains the defined characters only")
    else:
        print("The string does not contain the defined characters only")

regex_pattern = re.compile('^[Python]+$')
my_string_1 = 'Python'
print("The string is :")
print(my_string_1)
check_string(my_string_1, regex_pattern)

my_string_2 = 'PythonInterpreter'
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2, regex_pattern)

ผลลัพธ์

The string is : Python
The string contains the defined characters only
The string is : PythonInterpreter
The string does not contain the defined characters only

คำอธิบาย

  • Pattern ^[Python]+$ หมายถึง: เริ่มต้น (^) จบ ($) ประกอบด้วยตัวอักษรในชุด [P,y,t,h,o,n] เท่านั้น 1 ตัวขึ้นไป (+)
  • re.compile() คอมไพล์ pattern เพื่อใช้ซ้ำได้
  • re.search() ค้นหา pattern ในสตริง
  • 'PythonInterpreter' มีตัวอักษรนอกชุด (I, e, r, ...) จึงไม่ผ่าน