Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tìm kiếm từ chính xác với REGEXP trong MySQL

Giới thiệu

Sử dụng biểu thức chính quy REGEXP để tìm từ khóa xuất hiện như một từ riêng biệt (word boundary), không phải một phần của từ khác.

1. Tạo bảng và dữ liệu

mysql> create table DemoTable (
    -> Title varchar(255)
    -> ); 
Query OK, 0 rows affected (1.82 sec)

mysql> insert into DemoTable values('John is a good player'); 
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values('No,John Doe is not a good player'); 
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Yes,Adam Smith is play cricket match'); 
Query OK, 1 row affected (0.28 sec)
mysql> alter table DemoTable add fulltext(Title); 
Query OK, 0 rows affected, 1 warning (10.60 sec)
Records: 0 Duplicates: 0 Warnings: 1

2. Dữ liệu gốc

mysql> select *from DemoTable;
+--------------------------------------+
| Title                                |
+--------------------------------------+
| John is a good player                |
| No,John Doe is not a good player     |
| Yes,Adam Smith is play cricket match |
+--------------------------------------+
3 rows in set (0.00 sec)

3. Tìm từ "John" xuất hiện độc lập (không phải một phần "Johnson")

mysql> select *from DemoTable 
    -> where Title REGEXP '^.*John.*$';

Pattern '^.*John.*$':

  • ^: Đầu chuỗi
  • .*: Bất kỳ ký tự nào (0 hoặc nhiều)
  • John: Từ khóa cần tìm
  • .*$: Bất kỳ ký tự nào đến cuối chuỗi
  • Tương đương Title LIKE '%John%' nhưng REGEXP mạnh hơn

4. Kết quả

+----------------------------------+
| Title                            |
+----------------------------------+
| John is a good player            |
| No,John Doe is not a good player |
+----------------------------------+
2 rows in set (0.11 sec)

Tìm từ chính xác (word boundary) - tốt hơn:

WHERE Title REGEXP '[[:<:]]John[[:>:]]'
-- [[:<:]] = word boundary đầu, [[:>:]] = word boundary cuối
-- Khớp "John" nhưng KHÔNG khớp "Johnson", "Johnny"

MySQL 8.0+ hỗ trợ PCRE:

WHERE Title REGEXP '\\bJohn\\b'  -- \b = word boundary chuẩn PCRE

So sánh LIKE vs REGEXP vs FULLTEXT:

LIKEREGEXPFULLTEXT
Word boundaryKhóDễ ([[:<:]]/[[:>:]] hoặc \b)Tự động
Hiệu suấtTrung bìnhChậm (không dùng index)Nhanh (có index)
UnicodeTốtHạn chế (MySQL < 8.0)Tốt (ngram parser)