I have a string like below
this is a test string #1# random string #2# random string #30# random string #99#
the number is between #, the number can go from 1-99. the number is normally continuous from 1 to X, like #1#, #2#, #3#, #4#, but it could skip some numbers like #1#, #5#, #99#
I also have a dictionary like:
var dictionary = new Dictionary<int, string>()
{
{ 1, "value1" },
{ 2, "value2" },
{ 3, "value3" },
{ 4, "value4" },
};
I am looking for a regex to replace #X# with valueX, like #1# #2# #4#
will be replaced as value1 value2 value4
what I have tried is
if(orgStr.contain("#1#")
orgStr=orgStr.replace("#1#","value1")
if(orgStr.contain("#2#")
orgStr=orgStr.replace("#2#","value2")
it works but obviously not optimal
Any idea how to do it with C# regex?
CodePudding user response:
It seems to me that the effort to create a Regex
will produce more code than simply manipulating the string directly.
Try this:
var dictionary = new Dictionary<int, string>()
{
{ 1, "value1" },
{ 2, "value2" },
{ 3, "value3" },
{ 4, "value4" },
};
var text = "#1# #2# #4#";
text =
Enumerable
.Range(1, 99)
.Aggregate(text, (t, n) =>
dictionary.ContainsKey(n)
? t.Replace($"#{n}#", dictionary[n])
: t);
Console.WriteLine(text);
That produces:
value1 value2 value4
Here's the Regex
version:
var regex = new Regex("#(\\d{1,2})#");
text = regex.Replace(text, m =>
dictionary.ContainsKey(int.Parse(m.Groups[1].Value))
? dictionary[int.Parse(m.Groups[1].Value)]
: m.Value);
Or:
text = regex.Replace(text, m =>
dictionary
.TryGetValue(int.Parse(m.Groups[1].Value), out string value)
? value
: m.Value);
Here's a simple loop approach:
for (int n = 1; n <= 99; n )
{
if (dictionary.ContainsKey(n))
{
text = text.Replace($"#{n}#", dictionary[n]);
}
}
CodePudding user response:
You could use String.Replace() on each match found.
Like this:
var dictionary = new Dictionary<int, string>() {
{ 1, "value1" },
{ 2, "value2" },
{ 3, "value3" },
{ 4, "value4" },
};
string input = "some #1# string to compare to";
// Using RegEx
var rx = new Regex("\\#([0-9] )\\#", RegexOptions.Compiled);
MatchCollection matches = rx.Matches(input);
// Checking all matches
foreach (Match match in matches) {
// Getting the key
int key = int.Parse(match.Groups[1].Value);
input = input.Replace(match.Value, dictionary[key]);
}
This was written on my phone without prior testing so please do let me know if it works for you.