类似Google高级搜索的c#正则表达式
本文关键字:正则表达式 搜索 Google 高级 类似 | 更新日期: 2023-09-27 18:10:27
我试着写——没有运气——正则表达式能够从字符串中提取过滤条件,如:
String rawFilter = "field1: something field3: something else field2: any number of words";
字段可以以任意顺序出现,我需要提取某种键值对列表。
更新,根据评论的要求。就我对正则表达式的了解而言,第一个输出可能是一个数组,字段名位于偶数位置,值位于奇数位置。所以:
Console.WriteLine(matches[0]); //Prints field1
Console.WriteLine(matches[1]); //Prints something
Console.WriteLine(matches[2]); //Prints field3
Console.WriteLine(matches[3]); //Prints something else
Console.WriteLine(matches[4]); //Prints field2
Console.WriteLine(matches[5]); //Prints any number of words
字段名在组1中,值在组2中:
Regex r = new Regex(@"(field'd:)'s*((?:(?!field).)*)");
int i = 0;
foreach (Match m in r.Matches("field1: something field3: something else field2: any number of words")) {
Console.WriteLine(++i);
Console.WriteLine("{0} -{1}", 1, m.Groups[1].Value);
Console.WriteLine("{0} -{1}", 2, m.Groups[2].Value);
}
打印:
1
1 -field1:
2 - something
2
1 -field3:
2 - something else
3
1 -field2:
2 - any number of words