DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on

3

Regular Expression for match empty string

วันนี้มีโจทย์ให้ต้อง validate query string ของ API ให้รับแค่ string ที่มี A-Za-z0-9 ที่ต้องมี 3 ตัวอักษร เช่น "ABC", "A9C" หรือ empty string "" เท่านั้น สิ่งที่ช่วยได้นั่นคือ Regular Expression นั่นเอง

สำหรับ RegEx ที่ match A-Za-z0-9 จำนวน 3 ตัวอักษรนั้นไม่ยาก เขียนได้แบบนี้

[A-Za-z0-9]{3}
Enter fullscreen mode Exit fullscreen mode

โดยที่ [] ใช้กำหนดว่าจะรองรับ character แบบไหนบ้าง และ {3} เป็นการกำหนดจำนวนว่าต้องมีขนาด 3 ตัวอักษร

สำหรับ RegEx ที่ match empty string นั้นง่ายกว่าที่คิด เพราะเขียนแค่นี้

^$
Enter fullscreen mode Exit fullscreen mode

^ เป็นสัญลักษณ์กำหนดอักษรขึ้นต้น และ $ กำหนดอักษรสุดท้าย พอเอาสองตัวนี้มาติดกันแล้วไม่มีอักษรอะไรคั่น ก็ทำให้มันรองรับ empty string ได้นั่นเอง

สุดท้าย เราต้องการรองรับทั้งสองแบบนี้อย่างใดอย่างหนึ่ง RegEx นั้นใช้สัญลักษณ์ | แทน or เพื่อบอกว่าจะ match pattern ทางซ้ายหรือขวาก็ได้เช่นกัน กลายเป็น RegEx ที่ต้องการมีหน้าตาแบบนี้

^$|[A-Za-z0-9]{3}
Enter fullscreen mode Exit fullscreen mode

ขอฝาก Buy Me a Coffee

สำหรับท่านใดที่อ่านแล้วชอบโพสต์ต่างๆของผมที่นี่ ต้องการสนับสนุนค่ากาแฟเล็กๆน้อยๆ สามารถสนับสนุนผมได้ผ่านทาง Buy Me a Coffee คลิ๊กที่รูปด้านล่างนี้ได้เลยครับ

Buy Me A Coffee

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Retry later