MySQL/PostgreSQL中的正则表达式


之前用数据库用的比较少,没怎么实际用过MySQL中的rlike语句,最多也就like进行个模糊匹配,但最近碰到了rlike,觉得比较有意思,就多看了些内容,记录如下:

1.MySQL中的like语句

http://www.sqlexamples.info/PHP/mysql_rlike.htm

The wildcards used with LIKE are:

  • % substitute for unlimited amount of characters at the BEGINING/END of the string.
  • _ substitute for one character

==

2.[MySQL]String Regular Expression Operators
Name Description
NOT REGEXP Negation of REGEXP
REGEXP Pattern matching using regular expressions
RLIKE Synonym for REGEXP

Regular expressions in MySQL are invoked with the REGEXP keyword, aliased to RLIKE. The most basic usage is a hardcoded regular expression in the right hand side of a conditional clause, e.g.:

SELECT * FROM users WHERE email RLIKE '^[a-c].*[0-9]@';

Additionally, MySQL supports POSIX regular expressions, not PCRE like Ruby. There are things (like negative lookaheads) that you simply can’t do, though you probably ought not to be doing them in your SQL anyway.

==

3.[PostgreSQL]Regular Expression Match Operators
Operator Description Example
~ Matches regular expression, case sensitive ‘thomas’ ~ ‘.*thomas.*’
~* Matches regular expression, case insensitive ‘thomas’ ~* ‘.*Thomas.*’
!~ Does not match regular expression, case sensitive ‘thomas’ !~ ‘.*Thomas.*’
!~* Does not match regular expression, case insensitive ‘thomas’ !~* ‘.*vadim.*’

IN POSTGRESQL

Support for regular expressions in PostgreSQL is similar to that of MySQL, though the syntax is different (e.g. email ~ ‘^a’ instead of email RLIKE ‘^a’). What’s more, Postgres contains some useful functions for working with regular expressions, like substring andregexp_replace. See the documentation for more information.

==

实际测试:

mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 5.5.41-0ubuntu0.14.04.1 |
+-------------------------+
1 row in set (0.01 sec)

mysql> select "4270202235500236" rlike '^[0-9]{12,19}$';
mysql> select "4270202235500236" rlike '^([0-9]{4}( |-)?){4}$';
mysql> select "4270 2022 3550 0236" rlike '^([0-9]{4}( |-)?){4}$';
mysql> select "4270-2022-3550-0236" rlike '^([0-9]{4}( |-)?){4}$';
参考链接:

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注