C#查找字符串中的变量

时间:2015-08-20 19:24:23

标签: c# string

我有一个包含以下信息的字符串

[Messaging]
    Gatekeeper = "${Const|BaseURL}:${Const|PublicPort}"

[AvatarService]
    AvatarServerURI = "${Const|BaseURL}:${Const|PrivatePort}"

我如何查看网守的字符串并输出网守的值?

所以前 查看gatekeeper的字符串应生成${Const|BaseURL}:${Const|PrivatePort}的结果,不带引号。

1 个答案:

答案 0 :(得分:1)

您可以使用它来提取设置:

var settings = Regex.Split(settings_received_from_server, @"(?=\[\w+\])")
    .ToDictionary(
        section => Regex.Match(section, @"\[(?<section>\w+)\]").Groups["section"].Value,
        section => section.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
            // remove empty line or section header
            .Where(line => !string.IsNullOrWhiteSpace(line) && !Regex.IsMatch(line, @"\[.+\]"))
            // see note below
            .Select(line => Regex.Match(line, @"(?<key>\w+)\s*=\s*(?<value>.+)"))
            .ToDictionary(
                match => match.Groups["key"].Value,
                match => match.Groups["value"].Value));

// to get the setting use the following : [section][key]
settings["AvatarService"]["AvatarServerURI"]

注意:默认情况下,如果您还有不带引号的值,则保留双引号。

如果您想删除双引号,请使用以下正则表达式:

@"(?<key>\w+)\s*=\s*\""(?<value>.+)\"""