Pattern Matching with Regular Expressions
Problem
You want to perform a pattern match rather than a literal comparison.
Solution
Use the REGEXP operator and a regular expression
pattern, described in this section. Or use a SQL pattern, described
in Recipe 4.7.
Discussion
SQL patterns (see Recipe 4.7) are likely to be
implemented by other database systems, so they’re
reasonably portable beyond MySQL. On the other hand,
they’re somewhat limited. For example, you can
easily write a SQL pattern %abc% to find strings
that contain abc, but you cannot write a single
SQL pattern to identify strings that contain any of the characters
a, b, or c.
Nor can you match string content based on character types such as
letters or digits. For such operations, MySQL supports another type
of pattern matching operation based on regular expressions and the
REGEXP operator (or
NOT REGEXP to reverse the
sense of the match).[24]
REGEXP
matching uses a different set of pattern elements than
% and _ (neither of which is
special in regular expressions):
|
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 |
|
|
Alternation; matches any of the patterns
|
|
|
Zero or more instances of preceding element |
|
|
One or more instances of preceding element |
|
|
|
|
|
|
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access