Home > Net >  check if string contains dictionary keys and replace the matching subtring with Values from dictiona
check if string contains dictionary keys and replace the matching subtring with Values from dictiona

Time:12-04

I am parsing a template file which will contain certain keys that I need to map values to. Take a line from the file for example:

Field InspectionStationID 3 {"PVA TePla #WSM#", "sw#data.tool_context.TOOL_SOFTWARE_VERSION#", "#data.context.TOOL_ENTITY#"}

I need to replace the string within the # symbols with values from a dictionary. So there can be multiple keys from the dictionary. However, not all strings inside the # are in the dictionary so for those, I will have to replace them with empty string.

I cant seem to find a way to do this. And yes I have looked at this solution: check if string contains dictionary Key -> remove key and add value

For now what I have is this (where I read from the template file line by line and then write to a different file):

string line = string.Empty;
var dict = new Dictionary<string, string>() {
            { "data.tool_context.TOOL_SOFTWARE_VERSION", "sw0.2.002" },
            {"data.context.TOOL_ENTITY", "WSM102" }


        };
StringBuilder inputText = new StringBuilder();
StreamWriter writeKlarf = new StreamWriter(klarfOutputNameActual); 
using (StreamReader sr = new StreamReader(WSMTemplatePath)) 
{
    while((line = sr.ReadLine()) != null)
    {
        //Console.WriteLine(line);
        if (line.Contains("#"))
        {

        

        }
        else
        {
            writeKlarf.WriteLine(line)
        }
        
    }
}
writeKlarf.Close();

THe idea is that for each line, replace the string within the # and the # with match values from the dictionary if the #string# is inside the dictionary. How can I do this?

Sample Output Given the line above:

Field InspectionStationID 3 {"PVA TePla", "sw0.2.002", "WSM102"} 

Here because #WSM# is not the dictionary, it is replaced with empty string

One more thing, this logic only applies to the first qurter of the file. The rest of the file will have other data that will need to be entered via another logic so I am not sure if it makes sense to read the whole file in into memory just for the header section?

CodePudding user response:

Here's a quick example that I wrote for you, hopefully this is what you're asking for.

This will let you have a <string, string> Dictionary, check for the Key inside of a delimiter, and if the text inside of the delimiter matches the Dictionary key, it will replace the text. It won't edit any of the inputted strings that don't have any matches.

If you want to delete the unmatched value instead of leaving it alone, replace the kvp.Value in the line.Replace() with String.Empty

var dict = new Dictionary<string, string>() {
    { "test", "cool test" }
};

string line = "#test# is now replaced.";

foreach (var kvp in dict)
{
    string split = line.Split('#')[1];
    if (split == kvp.Key)
    {
        line = line.Replace($"#{split}#", kvp.Value);
    }

    Console.WriteLine(line);
}

Console.ReadLine();

CodePudding user response:

If you had a list of tuple that were the find and replace, you can read the file, replace each, and then rewrite the file

var frs = new List<(string F, string R)>(){
  ("#data.tool_context.TOOL_SOFTWARE_VERSION#", "sw0.2.002"),
  ("#otherfield#", "replacement here")
};

var i = File.ReadAllText("path");
frs.ForEach(fr => i = i.Replace(fr.F,fr.R));
File.WriteAllText("path2", i);

The choice to use a list vs dictionary is fairly arbitrary; List has a ForEach method but it could just as easily be a foreach loop on a dictionary. I included the ## in the find string because I got the impression the output is not supposed to contain ##..

This version leaves alone any template parameters that aren't available

CodePudding user response:

You can try matching #...# keys with a help of regular expressions:

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

  ...
         
static string MyReplace(string value, IDictionary<string, string> subs) => Regex
  .Replace(value, "#[^#]*#", match => subs.TryGetValue(
     match.Value.Substring(1, match.Value.Length - 2), out var item) ? item : "");

then you can apply it to the file: we read file's lines, process them with a help of Linq and write them into another file.

  var dict = new Dictionary<string, string>() {
    {"data.tool_context.TOOL_SOFTWARE_VERSION", "sw0.2.002" },
    {"data.context.TOOL_ENTITY",                "WSM102"    },
  };

  File.WriteAllLines(klarfOutputNameActual, File
    .ReadLines(WSMTemplatePath)
    .Select(line => MyReplace(line, dict)));    

Edit: If you want to switch off MyReplace from some line on

  bool doReplace = true;

  File.WriteAllLines(klarfOutputNameActual, File
    .ReadLines(WSMTemplatePath)
    .Select(line => {
       //TODO: having line check if we want to keep replacing
       if (!doReplace || SomeCondition(line)) {
         doReplace = false;

         return line;
       }

       return MyReplace(line, dict)
     })); 

Here SomeCondition(line) returns true whenever header ends and we should not replace #..# any more.

  •  Tags:  
  • c#
  • Related