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

MySQL: ตรวจสอบแถวที่มีคำ 2 คำพอดีด้วย REGEXP

การใช้ 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

Pattern แบบง่ายกว่า (MySQL 8.0+)

-- ใช้ word boundary (ต้องการ 2 คำพอดี)
WHERE Name REGEXP '^\\w+\\s+\\w+$'

-- หรือนับจำนวน space
WHERE LENGTH(Name) - LENGTH(REPLACE(Name, ' ', '')) = 1

ขยาย: N คำ

-- 3 คำ
REGEXP '^[^ ]+([ ][^ ]+){2}$'

-- N คำ (dynamic) - ต้องใช้ application logic สร้าง pattern

Case Sensitivity

  • MySQL REGEXP ค่าเริ่มต้น: Case-insensitive (ขึ้นอยู่กับ collation)
  • บังคับ Case-sensitive: REGEXP BINARY หรือ COLLATE utf8_bin

ประสิทธิภาพ

  • REGEXP ไม่ใช้ Index (Full table scan)
  • ตารางใหญ่: ควรเพิ่ม computed column word_count INT GENERATED ALWAYS AS (LENGTH(Name) - LENGTH(REPLACE(Name, ' ', '')) + 1) STORED แล้ว index คอลัมน์นี้

หมายเหตุ: Pattern นี้สมมติคำคั่นด้วย space เดียว หากมี tab, multiple spaces ให้ใช้ [[:space:]]+ แทน [ ]+

ส่วนRegexความหมาย
เริ่มต้น^เริ่มสตริง
คำแรก[^ ]+ตัวอักษรที่ไม่ใช่ space 1 ตัวขึ้นไป
Space[ ]+Space 1 ตัวขึ้นไป (รองรับหลาย space)
คำที่สอง[^ ]+ตัวอักษรที่ไม่ใช่ space 1 ตัวขึ้นไป
จบ$จบสตริง