Ajeet Ganga
Ajeet Ganga

Reputation: 8653

why this MySql regular expression not working?

SELECT 'AaYYY1231' REGEXP '[A-Z,0-9]+';

Result:

1

Why is it returning 1, when I expect it to return 0 ? From where is is it finding match for 'a' ?

Upvotes: 2

Views: 1918

Answers (1)

DreadPirateShawn
DreadPirateShawn

Reputation: 8402

http://dev.mysql.com/doc/refman/5.1/en/regexp.html

"REGEXP is not case sensitive, except when used with binary strings."

An example from the doc:

mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A';
+----------------+-----------------------+
| 'a' REGEXP 'A' | 'a' REGEXP BINARY 'A' |
+----------------+-----------------------+
|              1 |                     0 |
+----------------+-----------------------+

Additionally, it's not greedy, so it doesn't ensure that the entire string matches. Modifying the example above yields:

mysql> SELECT 'a' REGEXP BINARY '[A-Z0-9]+', 'Aa' REGEXP BINARY '[A-Z0-9]+';
+-------------------------------+--------------------------------+
| 'a' REGEXP BINARY '[A-Z0-9]+' | 'Aa' REGEXP BINARY '[A-Z0-9]+' |
+-------------------------------+--------------------------------+
|                             0 |                              1 |
+-------------------------------+--------------------------------+

To account for this, you can add flags for the beginning and end of the line:

mysql> SELECT 'Aa' REGEXP BINARY '^[A-Z0-9]+$';
+----------------------------------+
| 'Aa' REGEXP BINARY '^[A-Z0-9]+$' |
+----------------------------------+
|                                0 |
+----------------------------------+

This leads to the final answer of what you want:

mysql> SELECT 'AaYYY1231' REGEXP BINARY '^[A-Z,0-9]+$';
+------------------------------------------+
| 'AaYYY1231' REGEXP BINARY '^[A-Z,0-9]+$' |
+------------------------------------------+
|                                        0 |
+------------------------------------------+

Upvotes: 3

Related Questions