Removing substrings "dynamically" from a string in C #

I have a file with some lines in a text file like this

This is a test value with {MyTestValue = 0.34} How do I delete the test value? My line also has {MySecondTestValue = 0.35} 

The value of MyTestValue not the same value on each row.

Is there a way to determine the number of characters before the closing parenthesis and remove everything in parentheses. So my conclusion would be something like this:

 This is a test value with {} How do I delete the test value? My line also has {MySecondTestValue = 0.35} 
+5
source share
4 answers

Possible implementation using regular expressions:

 String source = "This is a test value with {MyTestValue = 0.34} How do I delete the test value?"; String result = Regex.Replace(source, "{.*}", (MatchEvaluator) ((match) => "{}")); 
+3
source
 string line="This is a test value with {MyTestValue = 0.34} How do I delete the test value?"; int index1=line.indexOf('{'); int index2=line.indexOf('}'); line=line.Replace(line.Substring(index1,index2-index1),""); 
+2
source

try it

 string output = Regex.Replace(input, @"{MyTestValue = [0-9.]+}", "{}"); 
+2
source

Stringbuilder is the most efficient way to work with strings. You can create a custom method that works with it:

  static string[] ClearValues(string[] dirtyLines, string[] ignoreValuesList) { string[] result = new string[dirtyLines.Length]; bool ignore = false; StringBuilder s = new StringBuilder(); StringBuilder s2 = new StringBuilder(); for (int i = 0; i < dirtyLines.Length; i++) { for (int i2 = 0; i2 < dirtyLines[i].Length; i2++) { if (dirtyLines[i][i2] == '{') { s2.Clear(); s.Append(dirtyLines[i][i2]); ignore = true; continue; } if (dirtyLines[i][i2] == '}') { if(ignoreValuesList.Contains(s2.ToString())) s.Append(s2.ToString()); s.Append(dirtyLines[i][i2]); ignore = false; continue; } if (!ignore) { s.Append(dirtyLines[i][i2]); } else { s2.Append(dirtyLines[i][i2]); } } result[i] = s.ToString(); s.Clear(); } return result; } 

Usage example:

  static void Main() { string[] dirtyLines = { "This is a test value with {MyTestValue = 0.34} How do I delete the test value?", "This is {SomeOther = 11} How do I delete the test value?", "{X = 134} How do {Y = 500} I delete the {Z = 400}test value?", }; Stopwatch s = new Stopwatch(); s.Start(); string[] clean = ClearValues(dirtyLines, new[] { "Y = 500", "Z = 400" }); s.Stop(); for (int i = 0; i < clean.Length; i++) { Console.WriteLine(clean[i]); } Console.WriteLine("\nIt took {0} ms and {1} CPU ticks for method to execute", s.ElapsedMilliseconds, s.ElapsedTicks); Console.ReadKey(); } 

Output:

enter image description here

0
source

All Articles