I have the following query:
SELECT *
FROM `shop`
WHERE `name` LIKE '%[0-9]+ store%'
I wanted to match strings that says '129387 store'
, but the above regex doesn't work. Why is that?
Use REGEXP operator instead of LIKE operator
Try this:
SELECT '129387 store' REGEXP '^[0-9]* store$';
SELECT * FROM shop WHERE `name` REGEXP '^[0-9]+ store$';
Check the SQL FIDDLE DEMO
OUTPUT
| NAME |
|--------------|
| 129387 store |
If you mean MySQL, LIKE
does not implement regular expressions. It implements the much more restricted SQL pattern matching, which just has two special operators: %
matches any sequence of characters, and _
matches any single character.
If you want regular expression matching, you must use the REGEXP
or RLIKE
operator:
SELECT *
FROM shop
WHERE name REGEXP '[0-9]+ store'
MySQL's regular expression language doesn't include \d
to specify digits, but you could write that as:
SELECT *
FROM shop
WHERE name REGEXP '[[:digit:]]+ store'
If the store name must begin with digits, you need an anchor:
SELECT *
FROM shop
WHERE name REGEXP '^[0-9]+ store'
You can learn more about regular expression syntax at regular-expressions.info.
Try
SELECT *
FROM `shop`
WHERE `name` LIKE '%[0-9] store%'
来源:https://stackoverflow.com/questions/20794860/regex-in-sql-to-detect-one-or-more-digit