MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. Following is the table of pattern, which can be used along with the REGEXP operator to handle the pattern matching.
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 |
Example
To illustrate the use of REGEXP we are using the table ‘Student_info’ having the following data −
mysql> Select * from Student_info; +------+---------+------------+------------+ | id | Name | Address | Subject | +------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | +------+---------+------------+------------+ 5 rows in set (0.00 sec)
Now, followings are some queries that use the REGEXP to find the patterns of ‘Name’ from the above table −
mysql> Select Name from student_info WHERE Name REGEXP '^Y'; +---------+ | Name | +---------+ | YashPal | +---------+ 1 row in set (0.11 sec)
The above query will find all the names starting with ‘Y’.
mysql> Select name from student_info WHERE Name REGEXP 'am$'; +-------+ | name | +-------+ | Ram | | Shyam | +-------+ 2 rows in set (0.00 sec)
The above query will find all the names ending with ‘am’.
mysql> Select name from student_info WHERE Name REGEXP 'av'; +--------+ | name | +--------+ | Gaurav | +--------+ 1 row in set (0.00 sec)
The above query will find all the names containing ‘av’.
mysql> Select name from student_info WHERE Name REGEXP '^[aeiou]|am$'; +-------+ | name | +-------+ | Ram | | Shyam | +-------+ 2 rows in set (0.00 sec)
Above query will find all the names starting with a vowel and ending with ‘am’.