C# 从占位符C获取字符串值#

C# 从占位符C获取字符串值#,c#,.net,regex,matching,C#,.net,Regex,Matching,我有模式字符串:“你好{Name},欢迎来到{Country}” 还有一个完整的值字符串:“你好,斯科特,欢迎来到越南” 如何提取{Name}和{Country}的值: 姓名=斯科特,国家=越南 我看到了一些正则表达式来解决这个问题,但是我可以在这里应用模糊匹配吗?例如,使用反转字符串“欢迎来到越南,你好Scott”,我们也必须更改正则表达式?您可以使用正则表达式: var Matches = Regex.Matches(input, @"hello\s+?([^\s]*)\s*|welcome

我有模式字符串:“你好{Name},欢迎来到{Country}
还有一个完整的值字符串:“你好,斯科特,欢迎来到越南”
如何提取{Name}和{Country}的值:
姓名=斯科特,国家=越南
我看到了一些正则表达式来解决这个问题,但是我可以在这里应用模糊匹配吗?
例如,使用反转字符串“欢迎来到越南,你好Scott”,我们也必须更改正则表达式?

您可以使用正则表达式:

var Matches = Regex.Matches(input, @"hello\s+?([^\s]*)\s*|welcome\s+?to\s+?([^\s]*)", RegexOptions.IgnoreCase);

string Name = Matches.Groups[1].Value;
string Country  = Matches.Groups[2].Value;

更新:更改了代码,使其能够以任何方式工作

只是又快又脏

string pattern = "Hello Scott, welcome to VietNam";

var splitsArray = pattern.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
var Name = splitsArray[1].Replace(",", string.Empty);
var country = splitsArray[4];

作为更通用的解决方案,您可以执行以下操作:

public Dictionary<string, string> GetMatches(string pattern, string source)
{
    var tokens = new List<string>();
    var matches = new Dictionary<string, string>();

    pattern = Regex.Escape(pattern);

    pattern = Regex.Replace(pattern, @"\\{.*?}", (match) =>
        {
            var name = match.Value.Substring(2, match.Value.Length - 3);

            tokens.add(name);

            return $"(?<{name}>.*)";
        });

    var sourceMatches = Regex.Matches(source, pattern);

    foreach (var name in tokens)
    {
        matches[name] = sourceMatches[0].Groups[name].Value;
    }

    return matches;
}
公共字典GetMatches(字符串模式,字符串源)
{
var tokens=新列表();
var matches=newdictionary();
pattern=Regex.Escape(模式);
pattern=Regex.Replace(pattern,@“\\{.*?}”,(match)=>
{
var name=match.Value.Substring(2,match.Value.Length-3);
标记。添加(名称);
返回$”(?*)”;
});
var sourceMatches=Regex.Matches(源,模式);
foreach(令牌中的变量名称)
{
matches[name]=sourceMatches[0]。组[name]。值;
}
返回比赛;
}

该方法从模式中提取标记名,然后使用名为capture group的正则表达式的等效语法替换标记。接下来,它使用修改后的模式作为正则表达式从源字符串中提取值。最后它使用捕获的令牌名称和命名的捕获组来构建一个要返回的字典。

我投票将这个问题作为主题外的问题来结束,因为它不包含再现问题的最小代码。我曾尝试使用正则表达式,但实际的问题是如何在不太频繁更改的情况下以常规方式提取值expression@phuongnd更新的答案,它将双向工作。更好的是,使用正则表达式从模板中提取令牌,并构建一个新的正则表达式,其中原始令牌将替换为命名的捕获组,字符串的其余部分将转义。这是有史以来最好的解决方案!