dubs
dubs

Reputation: 6521

Enclose specific words with single quotes

I'm after a simple solution to quote text in a string with quotes.

For example:

DATEDIFF(Minutes, Lead.WhenCreated, @Today)

need to be updated to

DATEDIFF(Minutes, Lead.WhenCreated, '@Today')

If the source string is already has quotes for the token then no change should be made. There may be multiple tokens in the string and I won't know what the token value will be - only to say that it will start with the @ character.

My environment is Visual Studio C# 2008.

Hope some can help.

Thanks.

Upvotes: 1

Views: 507

Answers (3)

FailedDev
FailedDev

Reputation: 26940

resultString = Regex.Replace(subjectString, @"(@\b\w+\b)", "'$1'");

You can use this one. It will find all words that start with @ and add quotes to them.

Edit :

resultString = Regex.Replace(subjectString, @"((?<!')@\b\w+\b)", "'$1'");

To account for already quoted strings.

Upvotes: 1

Alexey
Alexey

Reputation: 919

Pattern:

(?<!')(@\w+)

Replacement:

'$1'

Upvotes: 0

El Ronnoco
El Ronnoco

Reputation: 11912

It look like you're building a SQL statement in C# code and then replacing the parameters yourself. You are probably better off using this method...

DataReader rdr;
using (SqlConnection con = new SqlConnection(MY_CONNECTIONSTRING)
{
    con.Open();
    string sql = "SELECT DATEDIFF(Minutes, Lead.WhenCreated, @Today) FROM tbl";
    using (SqlCommand cmd = new SqlCommand(sql, con))
    {
         cmd.Parameters.AddWithValue("@Today", datDateValue);
         rdr = cmd.ExecuteReader();
    }
}

This method is safer against malicious SQL Injection.

This is an article addressing the issue in C#

Upvotes: 0

Related Questions