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

Escape Parentheses ใน MySQL REGEXP และค้นหาค่าที่มีวงเล็บ

การเตรียมข้อมูล

mysql> CREATE TABLE DemoTable1908 (Code TEXT);

mysql> INSERT INTO DemoTable1908 VALUES
    ('MySQL(1)Database'), ('MongoDB 2 Database'), ('MySQL(3)Database'),
    ('SQL Server(10)Database'), ('MySQL 8 Database');

ค้นหา Pattern: MySQL(ตัวเลข)Database

mysql> SELECT * FROM DemoTable1908 
    WHERE Code REGEXP '^MySQL[(][0-9][)]Database';

ผลลัพธ์:

+------------------+
| Code             |
+------------------+
| MySQL(1)Database |
| MySQL(3)Database |
+------------------+

Escape Parentheses ใน Regex

MySQL Regex Dialect

  • ใช้ POSIX Regular Expressions
  • \ ต้อง Double Escape ใน String Literal: '\\('
  • Character Class [(] อ่านง่ายกว่า ไม่ต้อง Escape
  • MySQL 8.0+ รองรับ ICU Regex (Richer Features)

Pattern แยกส่วน

^MySQL[(][0-9][)]Database
^         เริ่มสตริง
MySQL     ตรงตัว "MySQL"
[(]       ตัว '(' ตรงตัว
[0-9]     ตัวเลข 1 หลัก
[)]       ตัว ')' ตรงตัว
Database  ตรงตัว "Database"
$         จบสตริง (Implicit)

ขยาย: รองรับหลายหลัก (10, 100)

-- [0-9]+ = ตัวเลข 1 หลักขึ้นไป
SELECT * FROM DemoTable1908 
WHERE Code REGEXP '^MySQL[(][0-9]+[)]Database';

จะ Match เพิ่ม: SQL Server(10)Database (ถ้า Pattern เริ่มต้นไม่ใช่ MySQL)

MySQL 8.0: REGEXP_SUBSTR

SELECT REGEXP_SUBSTR(Code, 'MySQL\\([0-9]+\\)') FROM DemoTable1908;
-- MySQL(1), MySQL(3), NULL, NULL, NULL
ตัวอักษรEscape Methodหมายเหตุ
([(] หรือ \(Character Class หรือ Backslash
)[)] หรือ \)Character Class หรือ Backslash
[ ][[], []]ใน Character Class
.*+?^$|\. \* ฯลฯBackslash ทั่วไป