I have a string pattern that is used to assemble an automatic file name. The pattern may contain several properties such as:
[UserName]
[ItemName]
[ItemId]
etc... When the name is to be created I get the properties' values and replace them in the pattern to get the desired name. For example:
var propertyDict = new Dictionary<string, string>()
{
["[UserName]"] = "John Smit",
["[ItemName]"] = "Berry 47",
["[ItemId]"] = "123456",
};
var namingPattern = "[UserName] @ [ItemName] (id: [ItemId])";
// Expected result "John Smit @ Berry 47 (id: 123456)"
This is easily solved with just one foreach
loop in which I replace any match of dictionary key with its respective value:
foreach (var kvp in propertyDict)
{
namingPattern = namingPattern.Replace(kvp.Key, kvp.Value);
}
What bothers me are cases in which the user has chosen an unexpected name that can break the logic. Consider the following case:
var propertyDict = new Dictionary<string, string>()
{
["[UserName]"] = "[ItemName]", // Username matches with one of the placeholders
["[ItemName]"] = "Berry 47",
["[ItemId]"] = "123456",
};
var namingPattern = "[UserName] @ [ItemName] (id: [ItemId])";
// Expected result "[ItemName] @ Berry 47 (id: 123456)"
// Actual result "Berry 47 @ Berry 47 (id: 123456)"
I found a way to fix this by using RegEx. My idea was to match all possible placeholders ("\[[a-zA-Z]+\]"
) before doing any string replacements and afterwards to begin replacing by first checking the Index of the matched string. This is however too verbose and annoying to read if someone else has to go through this logic in the future. Any ideas and suggestions ?
Thanks in advance!