C#中使用Regex.Split按特定规则分割含保留字的字符串
Splitting the String with C# Regex.Split
The tricky part here is avoiding splits on apostrophes inside values (like O' Brian) while correctly splitting at the closing quotes of each field. Here's a solution that targets only valid field boundaries:
Step-by-Step Explanation
We need to split on a closing single quote that's followed by spaces and one of your reserved words (plus an equals sign, to ensure it's a field start). Using a positive lookahead lets us target these boundaries without including the reserved word in the split separator.
Code Implementation
using System; using System.Linq; using System.Text.RegularExpressions; class FieldSplitter { static void Main() { string criteria = "NAME='Eduard O' Brian' COURSE='Math II' TEACHER = 'Chris Young' SCHEDULE='3' CAMPUS='C-1' "; string[] reservedWords = { "NAME", "COURSE", "TEACHER", "SCHEDULE", "CAMPUS" }; // Regex pattern: Match a closing quote followed by spaces and a reserved word + equals // Non-capturing group avoids extra entries in split result string splitPattern = $@"'(?=\s+(?:{string.Join("|", reservedWords)})\s*=)"; // Split the string string[] rawSegments = Regex.Split(criteria, splitPattern); // Clean up: Remove empty entries and trim whitespace var cleanedSegments = rawSegments .Where(segment => !string.IsNullOrWhiteSpace(segment)) .Select(segment => segment.Trim()); // Output the result foreach (var segment in cleanedSegments) { Console.WriteLine(segment); } } }
How the Regex Works
': Matches a single quote.(?=\s+(?:NAME|COURSE|TEACHER|SCHEDULE|CAMPUS)\s*=): Positive lookahead that verifies:\s+: One or more spaces after the quote.(?:...): Non-capturing group of your reserved words.\s*=: Zero or more spaces followed by an equals sign (confirms it's a field start).
This ensures we only split at valid field boundaries, ignoring apostrophes inside values like O' Brian.
Output
NAME='Eduard O' Brian' COURSE='Math II' TEACHER = 'Chris Young' SCHEDULE='3' CAMPUS='C-1'
内容的提问来源于stack exchange,提问作者Mercy
相关产品推荐
相关产品推荐

