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....
Arne Vajhøj - 30 Apr 2008 02:19 GMT
> To replace some substrings in a string value, i use Regex.Replace method
> mulptiple times like;
[quoted text clipped - 6 lines]
>
> 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
Marc Gravell - 30 Apr 2008 08:33 GMT
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;
});
}
}
Marc Gravell - 30 Apr 2008 08:50 GMT