c# - Replacing specific numbers with String.Replace or Regex.Replace -
just having little problem in attempting string or regex replace on specific numbers in string.
for example, in string
@1 having lunch @10 @11
i replace "@1", "@10" , "@11" respective values indicated below.
"@1" replace "@bob" "@10" replace "@joe" "@11" replace "@sam"
so final output like
"@bob having lunch @joe @sam"
attempts
string.replace("@1", "@bob")
results in following
@bob having lunch @bob0 @bob1
any thoughts on solution might be?
assuming placeholder start @
, contain digits, can use regex.replace overload accepts matchevaluator delegate pick replacement value dictionary:
var regex = new regex(@"@\d+"); var dict = new dictionary<string, string> { {"@1","@bob"}, {"@10","@joe"}, {"@11","@sam"}, }; var input = "@1 having lunch @10 @11"; var result=regex.replace(input, m => dict[m.value]);
the result "@bob having lunch @joe @sam"
there few advantages compared multiple string.replace
calls:
- the code more concise, arbitrary number of placeholders
- you avoid mistakes due order of replacements (eg
@11
must come before@1
) - it's faster because don't need search , replace placeholders multiple times
- it doesn't create temporary strings each parameter. can issue server applications because large number of orphaned strings put pressure on garbage collector
the reason advantages 3-4 regex parse input , create internal representation contains indexes match. when time comes create final string, uses stringbuilder read characters original string substitute replacement values when match encountered.
Comments
Post a Comment