ชีตเช็คความรู้พื้นฐาน regex
นิพจน์เรกูลาร์ (regex) คือรูปแบบที่จับคู่กับข้อความ แต่ละสัญลักษณ์เรียกว่าโทเค็น จะเปลี่ยนพฤติกรรมของรูปแบบ ชีตด้านล่างรวบรวมโทเค็นที่ใช้บ่อยสุด พร้อมความหมายเรียบง่ายและตัวอย่างเล็กๆ นำไปคัดลอกทดสอบได้
| โทเค็น | ความหมาย | ตัวอย่าง |
|---|---|---|
| . | Matches any single character except newline. | a.c matches abc, a c |
| * | Matches the preceding token zero or more times. | ab* matches a, abb |
| + | Matches the preceding token one or more times. | ab+ matches ab, abb |
| ? | Makes the preceding token optional (zero or one). | colou?r matches color, colour |
| [] | Character set: matches any one character inside. | [aeiou] matches any vowel |
| [^] | Negated set: matches any character NOT inside. | [^0-9] matches any non-digit |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches any whitespace (space, tab, newline). | a\sb matches a b |
| ^ | Anchors the match to the start of a line/string. | ^Hello matches start of string |
| $ | Anchors the match to the end of a line/string. | world$ matches end of string |
| | | Alternation: matches the pattern on either side. | cat|dog matches cat or dog |
| () | Groups a sub-pattern (and captures it). | (ab)+ matches ab, abab |
| {n,m} | Quantifier: match the preceding token n to m times. | a{2,4} matches aa, aaaa |
| (?i) | Inline flag: makes the pattern case-insensitive. | (?i)hello matches HELLO |
หมายเหตุ
- โทเค็นส่วนใหญ่จะสูญเสียความหมายพิเศษภายในชุดอักขระ [ ] ตัวอย่างเช่น . ใน [ ] จับคู่เพียงจุดธรรมดา
- แบ็กสแลช (\) คืออักขระหลีก ที่เปลี่ยนโทเค็นพิเศษเป็นอักขระตัวเดิมและในทางกลับกัน
- เอนจิ้นแตกต่างกัน: Python, JavaScript, PCRE และ Golang ใช้โทเค็นส่วนใหญ่ร่วมกัน แต่การรองรับ flag และ look-around แตกต่างกัน
คำถามที่พบบ่อย
- จุด (.) จับคู่กับอะไร?
- ตามปกติจุดจะจับคู่กับอักขระใดก็ได้ยกเว้นขึ้นบรรทัดใหม่ หากต้องการจับคู่จุดธรรมดาให้ใส่แบ็กสแลชหลีกเป็น \
- * กับ + ต่างกันอย่างไร?
- ดอกจัน * จับคู่โทเค็นก่อนหน้าเป็นศูนย์ครั้งหรือมากกว่า จึงทำให้ 'ab*' จับคู่กับ 'a' ได้ด้วย ส่วนบวก + ต้องอย่างน้อยหนึ่งครั้ง จับคู่ 'ab' แต่ไม่ใช่ 'a' เดี่ยวๆ
- จะจับคู่ตัวเลขหรือตัวอักษรคำอย่างไร?
- ใช้ \d สำหรับตัวเลขใดก็ได้ (0-9) และ \w สำหรับตัวอักษรคำ (ตัวหนังสือ ตัวเลข ขีดล่าง) ตัวกลับกันคือ \D และ \W
- ^ และ $ ใช้ทำอะไร?
- ^ ตรึงการจับคู่ไว้ที่จุดเริ่มต้นของสตริงหรือบรรทัด $ ตรึงไว้ที่ท้าย เมื่อรวมกัน ^pattern$ บังคับให้สตริงทั้งหมดต้องจับคู่