การใช้ Regular Expression (REGEXP) ตรวจสอบสตริงที่มี 2 คำคั่น Space
Pattern '^[^ ]+[ ]+[^ ]+$' จับคู่สตริงที่: เริ่มต้นด้วย non-space 1+ ตัว → space 1+ ตัว → non-space 1+ ตัว → จบสตริง (พอดี 2 คำ)
สร้างตารางและข้อมูล
mysql> create table DemoTable1412 (
-> Name varchar(40)
-> );
Query OK, 0 rows affected (0.52 sec)
mysql> insert into DemoTable1412 values('John Adam Carol');
mysql> insert into DemoTable1412 values('Mike Sam');
mysql> insert into DemoTable1412 values('Chris James Robert');
ข้อมูลทั้งหมด
+--------------------+ | Name | +--------------------+ | John Adam Carol | | Mike Sam | | Chris James Robert | +--------------------+
คำสั่ง REGEXP
mysql> select * from DemoTable1412 where Name regexp '^[^ ]+[ ]+[^ ]+$';
ผลลัพธ์
+----------+ | Name | +----------+ | Mike Sam | +----------+
แยกวิเคราะห์ Pattern
| ส่วน | Regex | ความหมาย |
|---|---|---|
| เริ่มต้น | ^ | เริ่มสตริง |
| คำแรก | [^ ]+ | ตัวอักษรที่ไม่ใช่ space 1 ตัวขึ้นไป |
| Space | [ ]+ | Space 1 ตัวขึ้นไป (รองรับหลาย space) |
| คำที่สอง | [^ ]+ | ตัวอักษรที่ไม่ใช่ space 1 ตัวขึ้นไป |
| จบ | $ | จบสตริง |