I have string like
order by o desc,b asc
Here I want to replace o and b columns of this clause by table_o and table_b and output
order by table_o desc, table_b asc
I am using replace function for that but output becomes like
table_order table_by table_o desc,table_b asc
How to solve this problem using regular expression?
One more example
"order by orders desc, bye asc"
should be replaced as
"order by table_orders desc, table_bye asc"
Here is one possible solution. [You might have to tweak spaces around
descascand,based on your actual SQL]Result
Visual Regex

Regex details
(.*order by)?=> will match select a,b,c * from Table order by =>back ref $1(\\w+)=> will match column name =>back ref $2( desc| asc)?=> will match desc or asc => back ref $3(,|$)=> will match trailing comma or endof line => back ref $4Please Note : this solution only works with simple sql queries, and would produce wrong result if the
order byclause is part of inner query of a complex SQL. Moreover Regex is not can not ideal tool to parse SQL syntaxSee this link Regular expression to match common SQL syntax?
If full-fledged SQL parsing is required, Its better to use either SQL parsers or Parser generators like ANTLR to parse SQL. See this link for list of available ANTLR SQL grammer