Link to home
Start Free TrialLog in
Avatar of bishma
bishma

asked on

MySQL regex for matching comma seperated values

I have a string matching question that is beyond my knowledge when it comes to regex in mysql.

The Situation:
I have a rather large table with csv fields that needs to be searched and I need to be able to match rows according to 1+ user specified search terms. For example the user needs to be able to search for clock and radio. The issue is that I only want it to match separate comma separated values. So searching for clock and radio would only match were the field contains "clock, whatever, radio" and not "clock radio"

My thinking:
I need a regular expression that will match;
- the beginning of the string, a comma, or a space
- search term 1
- zero or more spaces
- then either a comma or the end of the string
then an OR and the same thing for search term 2.

Thank you in advance
Avatar of ozo
ozo
Flag of United States of America image

(^|[,[:space:]])clock[[:space:]]*(,|$)|(^|[,[:space:]])radio[[:space:]]*(,|$)
Avatar of bishma
bishma

ASKER

Here's what I'm doing
SELECT * FROM `myTable` WHERE `bedroom` REGEXP (^|,|[:space:])clock[[:space:]]*(,|$)|(^|,|[:space:])radio[[:space:]]*(,|$)

I altered you expression slightly because, I believe what you sent you would have mathched comma AND space vs. comma or space. But obviously I could be wrong.

MySQL said:
ERROR: Unknown Punctuation String @ 56
STR: ^|

Where did I screw up?

BTW I'm using mysql 4.1
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
,|[:space:] should be ,|[[:space:]] or [,[:space:]]
Avatar of bishma

ASKER

Worked perfectly. Thank you ozo, you're a gentleman/woman and a scholar.