Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding a number in space separated list with REGEXP

Tags:

regex

sql

mysql

I am writing a SQL query to select row, where a field with space separated numbers contains a single number, in this example the 1.

Example fields:

  • "1 2 3 4 5 11 12 21" - match, contains number one
  • "2 3 4 6 11 101" - no match, does not contain number one

The best query so far is:

$sql = "SELECT * from " . $table . " WHERE brands REGEXP '[/^1$/]' ORDER BY name ASC;";

Problem is that this REGEXP also finds 11 a match

I read many suggestions on other post, for instance [\d]{1}, but the result always is the same. Is it possible to accomplish what I want, and how?

like image 832
Lexib0y Avatar asked Jan 12 '23 14:01

Lexib0y


2 Answers

You don't need regex: You can use LIKE if you add a space to the front and back of the column:

SELECT * from $table
WHERE CONCAT(' ', brands, ' ') LIKE '% 1 %'
ORDER BY name
like image 142
Bohemian Avatar answered Jan 29 '23 19:01

Bohemian


Try:

WHERE brands REGEXP '[[:<:]]1[[:>:]]'

[[:<:]] and [[:>:]] match word boundaries before and after a word.

like image 27
Barmar Avatar answered Jan 29 '23 19:01

Barmar