Reputation: 4025
I was wondering if anyone can help me with a regular expression - not my strongest point - to parse the WHERE part of a SQL statement. I need to extract the column names, either in "column" or "table.column" format. I'm using MySQL and PHP.
For example, parsing:
(table.column_a = '1') OR (table.column_a = '0'))
AND (date_column < '2014-07-03')
AND column_c LIKE '%my search string%'
should yield
table.column_a
table.column_b
date_column
column_c
Edit: clarification - the strings will be parsed in PHP with preg_* functions!
Thank you!
Upvotes: 2
Views: 1611
Reputation: 41838
Assuming you are not doing this in SQL, you can use a regex like this:
[A-Za-z._]+(?=[ ]*(?:[<>=]|LIKE))
See regex demo.
This would work in Notepad++ and many languages.
Explanation
[A-Za-z._]+
matches the characters in your word (if you want to add digits, add 0-9
(?=[ ]*(?:[<>=]|LIKE))
asserts that what follows is optional spaces (the brackets are optional, they make the space stand out), then one of the characters in this class [<>=]
(an operator OR |
LIKE
[<>=]
, or tag them at the end with another alternation, e.g. |REGEXP
Reference
Upvotes: 4