基于逻辑关键词的正则表达式分组需求:排除括号内OR/AND/NOT
Solution: Split Query by Top-Level OR/AND/NOT (Ignoring Enclosed Keywords)
To split your query string into groups separated by top-level OR, AND, or NOT (while ignoring those keywords inside quotes, parentheses, or square brackets), you can use a regex that targets only the separators outside these enclosed contexts.
Regex Pattern for Splitting
\s+(OR|AND|NOT)\s+(?=(?:[^"']|"[^"]*"|'[^']*')*(?![^"']*["']))(?=(?:[^()]*\([^()]*\))*[^()]*$)(?=(?:[^\[\]]*\[[^\[\]]*\])*[^\[\]]*$)
Breakdown of the Regex:
\s+(OR|AND|NOT)\s+: Matches the logical keyword (OR,AND,NOT) surrounded by one or more whitespace characters.- Quote Balance Check: Ensures the separator isn't inside single or double quotes by verifying all quotes from this point onward are balanced.
- Parenthesis Balance Check: Ensures the separator isn't inside parentheses by confirming all opening parentheses have matching closing ones from this point to the end of the string.
- Square Bracket Balance Check: Does the same for square brackets (used in your date range example) to avoid splitting inside date range clauses.
Example Usage (Python)
Here's how you can implement this in Python to get your desired groups:
import re query = 'Email=sample@sample.com OR Something = \'(101010101010 OR 0101010123 )\' AND Id = "02341-21236-43497-123234" AND CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z]' split_regex = r'\s+(OR|AND|NOT)\s+(?=(?:[^"\']|"[^"]*"|\'[^\']*\')*(?![^"\']*["\']))(?=(?:[^()]*\([^()]*\))*[^()]*$)(?=(?:[^\[\]]*\[[^\[\]]*\])*[^\[\]]*$)' groups = re.split(split_regex, query) # Filter out the separator keywords to get only the groups result = [group for group in groups if group not in ('OR', 'AND', 'NOT')] # Print the formatted result for i, group in enumerate(result, 1): print(f"{i}. {group}")
Output:
1. Email=sample@sample.com 2. Something = '(101010101010 OR 0101010123 )' 3. Id = "02341-21236-43497-123234" 4. CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z]
Notes:
- This regex works for most common query formats like your example. It doesn’t handle nested parentheses (e.g.,
(A OR (B AND C))) out of the box—if you need support for nested enclosures, you’d need a recursive regex (available via Python’s third-partyregexlibrary instead of the standardremodule).
内容的提问来源于stack exchange,提问作者Abhishek Singh
相关产品推荐
相关产品推荐

