By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,885 Members | 1,499 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,885 IT Pros & Developers. It's quick & easy.

replace multiple strings at once

P: n/a
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....

Jun 27 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Ned White wrote:
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

Jun 27 '08 #2

P: n/a
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, stringargs = 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;
});
}
}
Jun 27 '08 #3

P: n/a
typo; should be a-zA-Z
Jun 27 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.