具有多个条件的分裂字符串

时间:2017-07-24 21:10:04

标签: c# .net regex

我有一个像这样的字符串 -

query = "UserId:(\"787D01FE-D108-4C83-A2E2-4B1DA3166A5C\" OR \"CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C\") AND CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z] OR FirstName: Abc ";

但是我希望像这样得到数组 -

queries=
{
   [0] UserId:(\"787D01FE-D108-4C83-A2E2-4B1DA3166A5C\" OR \"CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C\")
   [1] AND
   [2] CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z]
   [3] OR
   [4] FirstName: Abc 
}

更新:

到目前为止,我已经使用了这个 -

        var result =
                    (from Match m in Regex.Matches(query , @"\[[^]]*]|\{[^}]*}|[^:]+")
                         select m.Value)
                        .ToArray();

但以此结束 -

enter image description here

解决方案:

基于@NetMage建议的解决方案,我添加了一些更多的变体来处理双引号,括号内的条件Here

UserId  : ("787D01FE-D108-4C83-A2E2-4B1DA3166A5C" OR "CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C") AND CreatedDate : [ 2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z ] AND (FirstName  :   "Abc" OR LastName  :   "Xyz")

正则表达式 -

(?:\w+?\s*:\s*(\(.+?\)|\".+?\"|\[.+?\]|\w+))|(?:\(\w+?\s*:\s*(\(.+?\)|\".*?\"*|\[.+?\]|\w+)\))|([A-Z]+( [A-Z]+ )?)

1 个答案:

答案 0 :(得分:2)

这对你有什么用?

var pattern = @"(?:\w+? ?: ?(\(.+?\)|\[.+?\]|\w+))|([A-Z]+( [A-Z]+ )?)";

var ans = Regex.Matches(query, pattern).Cast<Match>().Select(m => m.Value).ToArray();