Regex guru help please?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Trying to wrap my brain around Regex for the first time...

I need to be able to replace Sql @NamedParameters with "?" for compliance
with an extremely lame 3rd party Odbc driver. I know that this should be
fairly straighforward in Regex but I'm not a Regex guru. Does anybody know
how to turn this {not real Sql but demonstrates my issue}:

SELECT * FROM Customers WHERE State=@State AND LastName LIKE @LastName

into this

SELECT * FROM Customers WHERE State=? AND LastName LIKE ?

using Regex? And for extra credit is it possible to have the search be
intelligent enough to NOT replace an @Xxx occurrence if it occurs within
quoted text?

Thanx in advance for any advice...

--Richard
 
FYI,

I tried using the expression "^@+" which I take to mean "matches if starts
with one or more @ characters". Since this and several variants on it are
not working for me I'm missing something here... Any ideas would be
appreciated...

--Richard
 
Hello:
using Regex? And for extra credit is it possible to have the search be
intelligent enough to NOT replace an @Xxx occurrence if it occurs within
quoted text?

In the Firebird .NET Provider i'm using this regex to do that:

(('[^']*?\@[^']*')*[^'@]*?)*(?<param>@\w+)*([^'@]*?('[^']*?\@*[^']*'))*

Hope it helps.
 
For the example you gave, this would work

=====================
string inputSql = "SELECT * FROM Customers WHERE State=@State AND LastName
LIKE @LastName
";

string outputSql = Regex.Replace(inputSql, @"(?i)@[^Xx\s]+", "?");
Console.WriteLine(outputSql);
=====================

This outputs:

"SELECT * FROM Customers WHERE State=? AND LastName LIKE ?"

Hope this helps!

Brian Delahunty
Ireland

http://briandela.com/blog
 
Back
Top