Regular expressions are a powerful tooI as most of you will agree but how does one use it with SQL queries ? Recently I had a requirement where I had to write a query that searches for the word “test” in a description field.
And it should also return the following matches : testing rocks So here is what I did. CREATE TABLE IF NOT EXISTS `test_reg` ( `PK_ID` int(10) NOT NULL AUTO_INCREMENT, `search_text` varchar(100) COLLATE latin1_general_ci NOT NULL PRIMARY KEY (`PK_ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=10 ; INSERT INTO `test_reg` (`PK_ID`, `search_text`) VALUES
|
Query for getting required output:
SELECT * FROM `test_reg` WHERE `search_text` REGEXP ‘(^(test)[^A-Za-z])|([^A-Za-z](test)[^A-Za-z])|([^A-Za-z](test)$)|(^(test)$)’ where (^(test)[^A-Za-z]) returns something like test<space><something> eg.”test some”, “test, my dog is testing”, “test123”, “test.”, “test,” etc |