我有一个类似下面的数据,我需要从该数据中提取密钥。
string filter=[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]
我检查了类似的情况,并且只能得到下面的代码,该代码未根据键给出结果
我尝试过
Regex.Match(filter, @"\[(.*?)\]")
如果我给Regn
,我需要得到Rasna
如果我给了LUB
,它应该给COMMERCIAL
并且像这样
答案 0 :(得分:1)
尝试以下操作:
string filter="[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]";
string pattern = @"\[(?'key'\w+),=,(?'value'[^\]]+)";
MatchCollection matches = Regex.Matches(filter, pattern);
foreach (Match match in matches.Cast<Match>())
{
Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
}
Console.ReadLine();
Dictionary<string, string> dict = matches.Cast<Match>().GroupBy(x => x.Groups["key"].Value, y => y.Groups["value"].Value)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
答案 1 :(得分:0)
如果要匹配单个值,可以使用正向后看和否定的字符类:
(?<=\[Regn,=,)[^]\r\n]+(?=\])
说明
(?<=\[Regn,=,)
[^]\r\n]+
否定的字符类,不匹配]
或换行符(添加您也不想匹配的字符((?=\])
断言右边是]
查看.NET regex demo或C# DEMO
string[] strings = { "LUB", "Pgm", "Regn", "Month", "Year", "Bywhat" };
foreach (string s in strings)
{
string filter = @"[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]";
string pattern = string.Format(@"(?<=\[{0},=,)[^]\r\n]+(?=\])", s);
var m = Regex.Match(filter, pattern);
Console.WriteLine(m.Value);
}
结果
COMMERCIAL
PRIVATE
Rasna
06
2018
M