Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex in SQL to detect one or more digit

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?

like image 339
adit Avatar asked Dec 27 '13 04:12

adit


People also ask

Can I use RegEx in SQL query?

You can use RegEx in many languages like PHP, Python, and also SQL. RegEx lets you match patterns by character class (like all letters, or just vowels, or all digits), between alternatives, and other really flexible options.

How do you represent a digit in RegEx?

\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).

How do I find a specific pattern in SQL?

LIKE clause is used to perform the pattern matching task in SQL. A WHERE clause is generally preceded by a LIKE clause in an SQL query. LIKE clause searches for a match between the patterns in a query with the pattern in the values present in an SQL table.


1 Answers

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 |
like image 93
Saharsh Shah Avatar answered Sep 21 '22 08:09

Saharsh Shah