Google高级搜索式C#正则表达式

时间:2011-10-04 10:49:58

标签: c# regex

我试着写 - 没有运气 - 正则表达式能够从字符串中提取过滤条件:

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 个答案:

答案 0 :(得分:2)

Fieldname在组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