为了账号安全,请及时绑定邮箱和手机立即绑定

mysql正则表达式使用实例

标签:
MySQL

Summary: in this tutorial, you will learn how to use MySQL regular expression with the SELECT statement to query data based on complex patterns.

Regular expression is a powerful tool that gives you a concise and flexible way to identify strings of text e.g., characters, words…etc based on patterns. For example, you can use regular expressions to search for email, IP address, phone number, social security number or anything that has specific pattern.

Regular expression is also known as regex. Regular expression uses its own syntax that can be interpreted by a regular expression processor. Regular expression is widely used in almost platforms from programming languages to databases including MySQL.

MySQL supports regular expression in the SQL statements, which you can search for strings of text by using special operator called REGEXP.  The following demonstrates the syntax of the REGEXP operator in the WHERE clause:

SELECT column_list  FROM table_name  WHERE column REGEXP pattern

The advantage of using regular expression is that you are not only limited to search for a string based on a fixed pattern like MySQL LIKE operator but also your own patterns.

The disadvantage of using regular expression is that it is quite difficult to understand and maintain such a complicated pattern. Therefore you should describe the meaning of regular expressions in the comments when using it in SQL statements. In some cases, the performance of data retrieval is decreased if you use complicated patterns in regular expression.

MySQL regular expression example

Let’s take a look at an example of using regular expressions in MySQL.

Suppose you want to find out employee whose last name starts with character M, B or T. You can use a regular expression in the SELECT statement as follows:

SELECT lastname, firstname  FROM employees WHERE lastname REGEXP  '^(M|B|T)';

mysql regular expression
The pattern allows you to find employee whose last name starts with character M, B or T.

  • The character ^ means to match from the beginning of the string.

  • The character | means to search for alternatives if one fails to match.

In this tutorial, you have learned how to query data from database table using MySQL regular expressions

Related Tutorials

原文链接:http://outofmemory.cn/mysql/tips/mysql-regular-expression-regexp

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消