เมื่อจำเป็นต้องตรวจสอบว่าสตริงที่ระบุมีอักขระเฉพาะโดยใช้นิพจน์ทั่วไปหรือไม่ จะมีการกำหนดรูปแบบนิพจน์ทั่วไป และสตริงจะต้องเป็นไปตามรูปแบบนี้
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
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 doesnot string contain the defined characters")
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 The string is : PythonInterpreter The doesn’t string contain the defined characters
คำอธิบาย
-
แพ็คเกจที่จำเป็นจะถูกนำเข้า
-
มีการกำหนดเมธอดที่ชื่อ 'check_string' และใช้สตริงและนิพจน์ทั่วไปเป็นพารามิเตอร์
-
วิธีการ 'ค้นหา' ถูกเรียกและตรวจสอบเพื่อดูว่ามีชุดอักขระเฉพาะอยู่ในสตริงหรือไม่
-
นอกเมธอด เมธอด 'คอมไพล์' จะถูกเรียกใช้ในนิพจน์ทั่วไป
-
สตริงถูกกำหนดและแสดงบนคอนโซล
-
เมธอดนี้เรียกโดยการส่งผ่านสตริงนี้
-
เอาต์พุตจะแสดงบนคอนโซล