Summarize some knowledge points of vue3: MySQL regular expression

MySQL regular expressions

In the previous chapters we have learned that MySQL can perform fuzzy matching through LIKE ...% .

MySQL also supports the matching of other regular expressions. MySQL uses the REGEXP operator for regular expression matching.

If you know PHP or Perl, it's pretty easy, since MySQL's regex matching is similar to those of these scripts.

The regular patterns in the following table can be applied to the REGEXP operator.

model describe
^ Matches the beginning of the input string. ^ also matches the position after '\n' or '\r' if the Multiline property of the RegExp object is set.
$ Matches the end of the input string. If the Multiline property of the RegExp object is set, $ also matches the position before '\n' or '\r'.
. Matches any single character except "\n". To match any character including '\n', use a pattern like '[.\n]'.
[...] collection of characters. Matches any one of the contained characters. For example, '[abc]' would match 'a' in "plain".
[^...] Negative character set. Matches any character not contained. For example, '[^abc]' would match the 'p' in "plain".
p1|p2|p3 Matches p1 or p2 or p3. For example, 'z|food' would match "z" or "food". '(z|f)ood' matches "zood" or "food".
* Matches the preceding subexpression zero or more times. For example, zo* would match "z" as well as "zoo". * is equivalent to {0,}.
+ Matches the preceding subexpression one or more times. For example, 'zo+' would match "zo" and "zoo", but not "z". + is equivalent to {1,}.
{n} n is a non-negative integer. Matches exactly n times. For example, 'o{2}' would not match the 'o' in "Bob", but would match both o's in "food".
{n,m} Both m and n are non-negative integers, where n <= m. Matches at least n times and at most m times.

example

After understanding the above regular requirements, we can write SQL statements with regular expressions according to our own needs. Below we will list several small examples (table name: person_tbl) to deepen our understanding:

Find all data starting with 'st' in the name field:


mysql> SELECT name FROM person_tbl WHERE name REGEXP '^st';

Find all data ending with 'ok' in the name field:


mysql> SELECT name FROM person_tbl WHERE name REGEXP 'ok$';

Find all data that contains the string 'mar' in the name field:


mysql> SELECT name FROM person_tbl WHERE name REGEXP 'mar';

Find all data in the name field that starts with a vowel character or ends with the string 'ok':


mysql> SELECT name FROM person_tbl WHERE name REGEXP '^[aeiou]|ok$';

Guess you like

Origin blog.csdn.net/2301_76147196/article/details/131460387