Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adapting a Regex to work with MySQL

Tags:

regex

mysql

I've got this Regex that works fine in all my testing, but I am unable to make it work in MySQL, despite the examples that I've been googling and trying variations of this:

^[A-Za-z]{2,4}-\d{3}-\d{2}$

In Javascript, it correctly matches AA-001-01 through ZZZZ-999-99, and so have tried it in MySQL with various tweaks to the regex, all with no luck:

SELECT * FROM products WHERE sku REGEXP '^[A-Za-z]{2,4}-\d{3}-\d{2}$'

(The table contains thousands of records where sku matches the samples given above)

As best as i can tell, Mysql Regex support is limited, but should this not work properly, or is there some further syntax consideration to work with Mysql?

like image 531
GDP Avatar asked Nov 17 '25 20:11

GDP


1 Answers

To match a digit you should use either [0-9] or [[:digit:]].

Try this:

SELECT col1, col2, ..., coln
FROM products
WHERE sku REGEXP '^[A-Za-z]{2,4}-[0-9]{3}-[0-9]{2}$'

See it working online: sqlfiddle.

See the manual for REGEXP.

like image 164
Mark Byers Avatar answered Nov 20 '25 13:11

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!