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

การใช้ MySQL RegEx ค้นหาบรรทัดที่มีอักขระเฉพาะจำนวน N ตัว

สามารถใช้ REGEXP ใน MySQL เพื่อค้นหาบรรทัดที่มีอักขระเฉพาะ (เช่น semicolon) จำนวน N ตัวได้

สร้างตารางตัวอย่าง

mysql> create table DemoTable ( 
    Id int NOT NULL AUTO_INCREMENT PRIMARY KEY , 
    Title text ); 
Query OK, 0 rows affected (0.88 sec)

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable(Title) values('This is; a; MySQL;Tutorial'); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Title) values('Java is; an;Object Oriented'); Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Title) values('MongoDB ; is;a; database'); Query OK, 1 row affected (0.12 sec)

แสดงข้อมูลทั้งหมด

mysql> select *from DemoTable;
+----+-----------------------------+
| Id | Title                       |
+----+-----------------------------+
|  1 | This is; a; MySQL;Tutorial  |
|  2 | Java is; an;Object Oriented |
|  3 | MongoDB ; is;a; database    |
+----+-----------------------------+
3 rows in set (0.00 sec)

RegEx ค้นหาบรรทัดที่มี semicolon (;) จำนวน 3 ตัว

mysql> select *from DemoTable where Title REGEXP '(.*;){3}';

ผลลัพธ์ (พบ 2 แถวที่มี ; ครบ 3 ตัว):

+----+----------------------------+
| Id | Title                      |
+----+----------------------------+
|  1 | This is; a; MySQL;Tutorial |
|  3 | MongoDB ; is;a; database   |
+----+----------------------------+
2 rows in set (0.00 sec)

คำอธิบาย Regular Expression

  • (.*;) - กลุ่มที่ match ตัวอักษรใดๆ 0 หรือมาก ตามด้วย semicolon
  • {3} - ระบุให้ match กลุ่มก่อนหน้าซ้ำ 3 ครั้ง
  • รูปแบบนี้จะ match กรณีมี semicolon อย่างน้อย 3 ตัว

รูปแบบ RegEx อื่นที่มีประโยชน์

  • ^(.*;){3}$ - มี semicolon อย่างแน่นอน 3 ตัว (ไม่มากกว่า)
  • ^[^;]*;[^;]*;[^;]*;[^;]*$ - แบบไม่ใช้ capturing group
  • REGEXP ';.*;.*;' - วิธีง่ายๆ สำหรับหาอย่างน้อย 3 ตัว

ประสิทธิภาพ

REGEXP อาจช้ากว่า LIKE ในตารางขนาดใหญ่ ควรทดสอบประสิทธิภาพก่อนนำไปใช้ใน Production