Mysqli-regexps
提供:Dev Guides
MySQLi-正規表現
- LIKE …%を使用したMySQLiパターンマッチングを確認しました。 MySQLiは、正規表現と *REGEXP 演算子に基づく別のタイプのパターンマッチング操作をサポートしています。 PHPまたはPERLを知っている場合、このマッチングはスクリプトの正規表現に非常に似ているため、理解するのは非常に簡単です。
以下は、 REGEXP 演算子とともに使用できるパターンの表です。
Pattern | What the pattern matches |
---|---|
^ | Beginning of string |
$ | End of string |
. | Any single character |
[…] | Any character listed between the square brackets |
[^…] | Any character not listed between the square brackets |
p1 | p2 |
p3 | Alternation; matches any of the patterns p1, p2, or p3 |
* | Zero or more instances of preceding element |
+ | One or more instances of preceding element |
{n} | n instances of preceding element |
\{m,n} | m through n instances of preceding element |
例
上記の表に基づいて、要件を満たすためにさまざまなタイプのSQLクエリを作成できます。 ここでは、あなたの理解のためにいくつかをリストしています。 tutorials_infというテーブルがあり、nameというフィールドがあると考えてください-
「sa」で始まるすべての名前を検索するクエリ
mysql> SELECT* FROM tutorials_inf WHERE name REGEXP '^sa';
サンプル出力は次のようになります-
+----+------+
| id | name |
+----+------+
| 1 | sai |
+----+------+
1 row in set (0.00 sec)
「ai」で終わるすべての名前を検索するクエリ
mysql> SELECT *FROM tutorials_inf WHERE name REGEXP 'ai$';
サンプル出力は次のようになります-
+----+------+
| id | name |
+----+------+
| 1 | sai |
+----+------+
1 row in set (0.00 sec)
「a」を含むすべての名前を検索するクエリ
mysql> SELECT* FROM tutorials_inf WHERE name REGEXP 'a';
サンプル出力は次のようになります-
+----+-------+
| id | name |
+----+-------+
| 1 | sai |
| 3 | ram |
| 4 | johar |
+----+-------+
3 rows in set (0.00 sec)
母音で始まるすべての名前を検索するクエリ
mysql> SELECT * FROM tutorials_inf WHERE name REGEXP '^[aeiou]';