MySQL Regular Expressions
Overview
MySQL provides regular expression support through the REGEXP and RLIKE operators for pattern matching in string data. Regular expressions are powerful tools for complex pattern matching.
Regular Expression Basics
- Pattern Matching: Match specific patterns in text
- Wildcards: Special characters for flexible matching
- Anchors: Position of match in string
- Character Classes: Sets of characters to match
REGEXP Operator
Basic Syntax
REGEXP vs LIKE
Regular Expression Metacharacters
Common Metacharacters
| Pattern
|-----------------|------------------|----------------|
| ^ | Start of string
| $ | End of string
| . | Any single character
| | | OR operator
| * | Zero or more occurrences
| + | One or more occurrences
| ? | Zero or one occurrence
| [ ] | Character class
| [^ ] | Negated character class
| \ | Escape character
Examples
Character Classes
Predefined Classes
| Class
|------------|------------------|
| [[:alnum:]] | Alphanumeric
| [[:alpha:]] | Alphabetic
| [[:digit:]] | Digits
| [[:lower:]] | Lowercase
| [::upper:]] | Uppercase
| [[:space:]] | Whitespace
| [::punct:]] | Punctuation
Examples
Practical Examples
Email Validation
Phone Number Matching
Product Codes
Text Search
REGEXP_REPLACE Function
MySQL 8.0+ supports REGEXP_REPLACE for substitution.
REGEXP_LIKE / REGEXP_LIKE
Simple pattern matching without full regex support.
Performance Considerations
REGEXP Performance
Alternative Approaches
Advanced Patterns
Capturing Groups
Word Boundaries
Repetition Quantifiers
REGEXP Case Sensitivity
Common Use Cases
Data Validation
Data Cleaning
Pattern Extraction
Summary
Regular expressions in MySQL provide:
- Powerful Pattern Matching: Complex patterns beyond LIKE
- Flexible Matching: Wildcards, character classes, anchors
- String Functions: REGEXP_REPLACE, REGEXP_SUBSTR (MySQL 8.0+)
- Search Capabilities: Email, phone, URL validation
Consider performance and use appropriate indexing when working with large datasets.
Previous: NULL Values
Next: Transactions