Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing regular expressions in MySQL database table and maching against them

Tags:

regex

php

mysql

I have a very interesting task, which I don't know how to implement.

I need to store many regular expressions in a database table, and need to be able to find which of them matches the given string.

For example:

id | regexp
---|-------------
1  | ^hello world$
2  | ^I have [0-9] flowers&
3  | ^some other regexp$ 
4  | ^and another (one|regexp)$

And I need to find which of those expressions matches string "I have 5 flowers". Of course I can SELECT * FROM table and loop through an expressions matching them one by one in PHP, but this would be horrible for server to handle.

Can I somehow index this table or use a special SQL query to handle this task?

I'll appreciate any answer. Thank you.

like image 954
Silver Light Avatar asked Mar 01 '10 09:03

Silver Light


2 Answers

select * from table where $your_string RLIKE regexp 

mysql regular expressions

like image 148
user187291 Avatar answered Nov 10 '22 17:11

user187291


SELECT * FROM table WHERE 'some stuff' REGEXP `regexp`;

Unfortunately there is no way to use indexes with queries that use regexps.

like image 26
Romuald Brunet Avatar answered Nov 10 '22 15:11

Romuald Brunet