replace multiple strings at once

  • Thread starter Thread starter Ned White
  • Start date Start date
N

Ned White

Hi All,

To replace some substrings in a string value, i use Regex.Replace method
mulptiple times like;

strmemo = "new Data for user; Name:@@Name , Surname:@@Surname,
Address:@@Address";
strmemo = Regex.Replace(strmemo,"@@Name", value1.ToString());
strmemo = Regex.Replace(strmemo,"@@Surname", value2.ToString());
strmemo = Regex.Replace(strmemo,"@@Address", value3.ToString());

are there any solutions to combine all these statements into just one.

Thanks....
 
Ned said:
To replace some substrings in a string value, i use Regex.Replace method
mulptiple times like;

strmemo = "new Data for user; Name:@@Name , Surname:@@Surname,
Address:@@Address";
strmemo = Regex.Replace(strmemo,"@@Name", value1.ToString());
strmemo = Regex.Replace(strmemo,"@@Surname", value2.ToString());
strmemo = Regex.Replace(strmemo,"@@Address", value3.ToString());

are there any solutions to combine all these statements into just one.

Not really.

You can:

strmemo = strmemo.Replace("@@Name",
value1.ToString())Replace("@@Surname",
value2.ToString()).Replace("@@Address", value3.ToString());

but it is still 3 replaces.

But why not:

strmemo = String.Format("new Data for user; Name:{0}, Surname:{1},
Address:{2}", value1.ToString(), value2.ToString(), value3.ToString());

it looks much better.

Arne
 
How about using a custom evaluator? Now all you need to do is add things
to the dictionary and they should work... For the record, you might also
want to handle escaping (i.e. how do yuo write @@Foo as a literal?), and
termintated tokens (i.e. you do you write a literal immediately after a
token - i.e. "@@Size" + "mm" (if you see what I mean) - @Size@mm would
be easier... (i.e. @Foo@ is a token for the argument Foo)

Marc

using System.Collections.Generic;
using System.Text.RegularExpressions;
static class Program
{
static readonly Regex regex = new Regex("(@@)([a-zA-z]+)",
RegexOptions.Compiled);
static void Main()
{
Dictionary<string, string> args = new Dictionary<string, string>();
args.Add("Surname", "Smith");
args.Add("Name", "John");
args.Add("Address", "Somewhere");

string input = "new Data for user; Missing:@@Missing,
Name:@@Name , Surname:@@Surname, Address:@@Address";

string output = regex.Replace(input, delegate(Match match)
{
string value;
args.TryGetValue(match.Groups[2].Value, out value);
return value;
});
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top