Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching MySQL database by a Regex match (in reverse)

Tags:

regex

mysql

If I have a database table that has one column that contains a regex pattern, is it possible to return rows (without systematically testing each row in turn) that a string matches?

for example, a table like this:

RowID     RegExPattern
1         foo\.$
2         bar\.$
3         baz\.$
4         (foo|bar)\.$

and an input string like this:

foo.php

will return RowIDs 1 and 4

like image 804
topherg Avatar asked Aug 20 '12 20:08

topherg


People also ask

Does MySQL support RegEx?

MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems.

How do I use RegEx to match?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Can you use RegEx in SQL Server?

Regular expressions are a concise and flexible notation for finding and replacing patterns of text. A specific set of regular expressions can be used in the Find what field of the SQL Server Management Studio Find and Replace dialog box.


1 Answers

If I have a database table that has one column that contains a regex pattern, is it possible to return rows [...] that a string matches?

Yes, that's possible.

SELECT RowID
FROM yourtable
WHERE 'foo.php' REGEXP RegExPattern

Note though that your regular expressions won't match. If you omit the $ then they will.

See it working online: sqlfiddle

(without systematically testing each row in turn)

Err... no. You need to test each row.

like image 82
Mark Byers Avatar answered Nov 15 '22 04:11

Mark Byers