-4

My application saves informations into a file like this:

[Name]{ExampleName}
[Path]{ExamplePath}
[Author]{ExampleAuthor}

I want to cut the [Name]{....} out and just get back the "ExampleName".

//This is what the strings should contain in the end.
string name = "ExampleName"
string path = "ExamplePath"

Is there any way to do this in C#?

ThePat02
  • 27
  • 1
  • 1
  • 6
  • See https://stackoverflow.com/questions/413071/regex-to-get-string-between-curly-braces-i-want-whats-between-the-curly-brace and https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets . – mjwills Jun 13 '17 at 13:36
  • Of course there's a way to do this in C#. Did you try anything regarding this problem you have? Please read https://stackoverflow.com/help/how-to-ask – Paul Karam Jun 13 '17 at 13:36
  • 1
    If you want to store structured data, why not to use the standard mechanisms like JSON serialization or XML serialization? – Gusman Jun 13 '17 at 13:37

3 Answers3

0

You could use a regular expression to cut out the string part between brackets:

var regex = new Regex("\[.*\]{(?<variableName>.*)}");

If you try matching this regular expression on your strings, you end up with your resulting strings in the match group 'variableName' (match.Groups["variableName"].Value).

DotBert
  • 1,262
  • 2
  • 16
  • 29
0

You can extract the keys and the values and push them into a dictionary that you can later easily access like this:

var text = "[Name]{ExampleName} [Path]{ExamplePath} [Author]{ExampleAuthor}";

// You can use regex to extract the Value/Pair
var rgx = new Regex(@"\[(?<key>[a-zA-Z]+)\]{(?<value>[a-zA-Z]+)}", RegexOptions.IgnorePatternWhitespace);
var matches = rgx.Matches(text);

// Now you can add the values to a dictionary
var dic = new Dictionary<string, string>();
foreach (Match match in matches)
{
    dic.Add(match.Groups["key"].Value, match.Groups["value"].Value);
}

// Then you can access your values like this.
var name = dic["Name"];
nramirez
  • 5,230
  • 2
  • 23
  • 39
-2

I'm not sure to understand what you need but I will try.

You can use this :

var regex = new Regex(Regex.Escape("Name"));
var newText = regex.Replace("NameExampleName", "", 1);