I’m surprised I didn’t find a duplicate of this question. I’m trying to parse out some sql strings and replace the first “SELECT… FROM ” string with a different string. I would think it wouldn’t be too difficult but haven’t hit on the solution yet. If my test string is:
' SELECT something, something_else FROM (SELECT somebody FROM some_table)'
and I want to replace it with:
' SELECT count(*) as total FROM (SELECT somebody FROM some_table)'
I’ve tried the following regex expressions using REReplaceNoCase():
<cfset SQL = #REReplaceNoCase(test, "^\s*(SELECT.*\s+FROM\s)??", "SELECT count(*) as total FROM ")# />
<cfset SQL = #REReplaceNoCase(test, "^\s*SELECT.*(\s+FROM\s)??", "SELECT count(*) as total FROM ")# />
<cfset SQL = #REReplaceNoCase(test, "^\s*SELECT.*\s+(FROM)??\s", "SELECT count(*) as total FROM ")# />
as well as some other variations. Suggestions?
I wouldn’t use replace here – easier (and more efficient) to just locate the first FROM and split the string into two parts at that point, then prepend your new string onto the front:
The regex uses a look-ahead so it matches the position before the FROM, and you don’t need to re-add it.
You can of course change the regex used for the split, if necessary.
For example, to make it case-insensitive and use spaces rather than word boundaries:
The second argument (2) is what tells split to stop after it has two strings (so the second array item contains the rest of the string, even if there might have been more FROMs in it).
Also note that this is the Java split method, and uses java.util.regex for the regex (which has some differences/improvements to CF’s Apache ORO regex).