基于关键字过滤的正则表达式

Regular expression for filtering based on a keyword

我想过滤字符串并根据关键字 ('OR'、'AND'、'NOT') 等进行分组,但不包括关键字 'OR'、'NOT'、'AND'等括号内。

Email=sample@sample.com OR Something = '(101010101010 OR 0101010123 )' AND Id = \"02341-21236-43497-123234\" AND CreatedDate:[2017-06-20T06:14: 11Z 至 2017-07-20T06:14:11Z]

输出组应该是这样的:

  1. Email=sample@sample.com
  2. 某事 = (101010101010 或 0101010123)
  3. Id = "02341-21236-43497-123234"
  4. 创建日期:[2017-06-20T06:14:11Z 至 2017-07-20T06:14:11Z]

这样的事情怎么样:

(?<=^|AND|OR)(?:[^()]+?|.+?\(.+?\).+?)(?=\s*AND|OR|$)

Try it online.

细分:

  • (?<=^|AND|OR) 断言前面的字符是 ANDOR 或字符串的开头。
  • (?: 非捕获组的开始。
    • [^()] 匹配除 ().
    • 之外的任何字符
    • +? 匹配前一个字符一次或多次(惰性匹配)。
    • | 或者.
    • .+? 匹配任意字符一次或多次(惰性匹配)。
    • \( 按字面匹配字符 (
    • .+? 匹配任意字符一次或多次(惰性匹配)。
    • \) 按字面匹配字符 )
    • .+? 匹配任意字符一次或多次(惰性匹配)。
  • )非捕获组结束。
  • (?=\s*AND|OR|$) 断言后面的字符是 ANDOR 或字符串的结尾。

C# 中的用法示例:

static List<string> ExtractParts(string input)
{
    string pattern = @"(?<=^|AND|OR)(?:[^()]+?|.+?\(.+?\).+?)(?=\s*AND|OR|$)";
    var matches = Regex.Matches(input, pattern);

    List<string> list = new List<string>();
    foreach (Match m in matches)
    {
        list.Add(m.Value.Trim());
    }

    return list;
}

static void Main(string[] args)
{
    string input = @"Email=sample@sample.com OR " +
                   @"Something = '(101010101010 OR 0101010123 )'" +
                   @" AND Id = \""02341 - 21236 - 43497 - 123234\""";
    List<string> parts = ExtractParts(input);
    foreach (string part in parts)
    {
        Console.WriteLine(part);
    }
    Console.ReadLine();
}

Live example.

希望对您有所帮助。