"剪掉"文件的特定文本并将其放入字符串中

时间:2017-06-13 13:34:01

标签: c# string visual-studio file

我的应用程序将信息保存到这样的文件中:

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

我想将[Name] {....}删除,然后返回" ExampleName"。

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

有没有办法在C#中执行此操作?

3 个答案:

答案 0 :(得分:0)

您可以使用正则表达式剪切括号之间的字符串部分:

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

如果您尝试在字符串上匹配此正则表达式,则最终会在匹配组中生成结果字符串&#39; variableName&#39; (match.Groups["variableName"].Value)。

答案 1 :(得分:0)

您可以提取密钥和值,并将它们推入字典中,以后可以轻松访问:

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"];

答案 2 :(得分:-2)

我不确定你需要什么,但我会尝试。

您可以使用:

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