从占位符 C# 中获取字符串值
Get string value from Placeholder C#
我有模式字符串:"你好{Name},欢迎来到{Country}"
和一个完整的值字符串:"你好斯科特,欢迎来到越南"
如何提取 {Name} 和 {Country} 的值:
姓名 = 斯科特,国家 = 越南
我看到一些正则表达式可以解决这个问题,但我可以在这里应用模糊匹配吗?
例如使用反转字符串“welcome to VietNam, Hello 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;
更新: 更改了代码以两种方式工作。 Demo.
只是又快又脏..
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;
}
该方法从模式中提取标记名称,然后将标记替换为名为捕获组的正则表达式的等效语法。接下来,它使用修改后的模式作为正则表达式从源字符串中提取值。最后,它使用捕获的令牌名称和命名的捕获组来构建要返回的字典。
我有模式字符串:"你好{Name},欢迎来到{Country}"
和一个完整的值字符串:"你好斯科特,欢迎来到越南"
如何提取 {Name} 和 {Country} 的值:
姓名 = 斯科特,国家 = 越南
我看到一些正则表达式可以解决这个问题,但我可以在这里应用模糊匹配吗?
例如使用反转字符串“welcome to VietNam, Hello 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;
更新: 更改了代码以两种方式工作。 Demo.
只是又快又脏..
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;
}
该方法从模式中提取标记名称,然后将标记替换为名为捕获组的正则表达式的等效语法。接下来,它使用修改后的模式作为正则表达式从源字符串中提取值。最后,它使用捕获的令牌名称和命名的捕获组来构建要返回的字典。