2

I have strings like below:

Insert into Emp(Id,Name,Number,Address) values({Id},"Abc",{Number},{Address});

In above string {Id} ,{Number} and {Address} are placeholders which I want to replace with some values.

I want list of placeholders from the string and I want to easily replace it with actual values.

output should be like this:

Insert into Emp(Id,Name,Number,Address) values(123,'Abc',55668878,'test address');
9
  • 4
    Have a look at string interpolation. BUT! better still - just use parameterized queries or some ORM to manage queries to database Commented Apr 2, 2019 at 11:26
  • If this is all about SQL statements I hardly recommend using parameters to avoide SQL Injection. Commented Apr 2, 2019 at 11:28
  • It's code demand. Commented Apr 2, 2019 at 11:30
  • Is it SQL question? or C# string interpolation question. Commented Apr 2, 2019 at 11:30
  • 3
    As a side note - it is more correct to call it place holders rather than macros Commented Apr 2, 2019 at 11:35

4 Answers 4

3

If you receive your string in a variable you should do interpolation by yourself

To do so, you need to find all placeholders and replace they value. You can do this with regular expression (can be simplified if placeholder can start with digits)

{(?<placeholder>[a-z_][a-z0-9_]*?)}

Next method will do this replacement:

public static string Replace(string input, Dictionary<string, object> replacement)
{
    var regex = new Regex("{(?<placeholder>[a-z_][a-z0-9_]*?)}",
        RegexOptions.Compiled | RegexOptions.IgnoreCase);

    return regex.Replace(input, m =>
    {
        var key = m.Groups["placeholder"].Value;
        if (replacement.TryGetValue(key, out var value))
            return value.ToString();

        throw new Exception($"Unknown key {key}");
    });
}

Usage:

var input = "Insert into Emp(Id,Name,Number,Address) values({Id},\"Abc\",{Number},{Address});";
var replaces = new Dictionary<string, object>
{
    {"Id", 123},
    { "Number", 55668878},
    {"Address", "\"test address\"" },
};

var result = Replace(input, replaces);
Console.WriteLine(result);

Ouput:

Insert into Emp(Id,Name,Number,Address) values(123,"Abc",55668878,"test address");

Sign up to request clarification or add additional context in comments.

Comments

2

If your string is already in the format of {variable} then it is perfect for using string interpolation:

var Id=1, Number=2;
var Address = "Some address";

string str = $"Insert into Emp(Id,Name,Number,Address) values({Id},\"Abc\",{Number},{Address});"

Another option, if you have many such strings, each with their own place holder collection is to iterate such collection of placeholder and use string.Replace between the placeholder and the desired value (for instance if this collection of placeholders is a lookup table with the key as the placeholder string and the values as the desired values).

However, as I commented, I really really encourage you to not use methods like this for creating your queries. This is risky as it is susceptible for SQL Injections. Instead use parameterized queries or better still some ORM to your database.

5 Comments

Guess you forgot to replace the @with an $ ;)
@MightyBadaboom - no :) Just a typo but thanks for pointing it out haha
This is good but First i want List of placeholders and accordingly i want to change the value.
Okay liked your recommendation. Just one more question how to apply $ on a string variable? Query i get is in string variable.
@Milanchavda - Not sure because I need to see the relevant code first. But this this a followup question and should be part of a separate SO question. Please try googling it to see if there are previously asked questions about the matter
2

One solution could be doing like this : You replace the {Id}, {Number}, {Address} by {0}, {1}, {2}, like this.

Insert into Emp(Id,Name,Number,Address) values({0},"Abc",{1},{2});

Then you do this :

myString = string.Format(myString, "123", "55668878", "test address");

With this solution you don't have to work with regex of complex things.

Comments

0

This is just an idea or you could a sample piece of code, for replacing tokens, you can use this logic as well.

    private string ReplaceTokens(string htmlBody, Dictionary<string, string> tokenValues)
{
    // Iterate through each token-value pair in the dictionary
    foreach (var token in tokenValues)
    {
        // Replace the token in the HTML body with its corresponding value
        htmlBody = htmlBody.Replace(token.Key, token.Value);
       ]
    }

    return htmlBody;
}

2 Comments

your solution almost works exept it leaves the currly braces in palce. Maybe use Replace("{" + token.Key + "}", token.Value)
Yes you are correct. I miss the logic there. It will work perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.