JavaScript正则拆分键值对及格式验证技术问询
Got it, let's work through this problem together. You need two core pieces: a way to validate that your input string follows the required format, and a regex-based method to split/parse the string into a clean array of key-value pairs. Your original regex only handled quoted pairs separated by commas, so we'll expand that to cover all your rules.
1. Format Validation Regex
First, let's ensure the input string is fully compliant with your rules:
- Every key must have a corresponding value
- Keys or values with spaces (or special characters like
,/=) must be wrapped in double quotes - Quoted values can include escaped quotes (
\") and commas without breaking the structure
Here's the validation regex, plus a helper function to use it:
function isValidKeyValueString(str) { // Regex breakdown: // - ^/$: Ensures we match the entire string // - (?: ... )+: Matches one or more key-value pairs // - (?:"([^"\\]|\\.)+"|([^\s,=]+)): Matches keys (quoted or unquoted) // - \s*=\s*: Matches the equals sign with optional surrounding whitespace // - Same pattern for values as keys // - \s*(?:,|$): Matches trailing commas (with spaces) or end of string const validationRegex = /^(?:\s*(?:"([^"\\]|\\.)+"|([^\s,=]+))\s*=\s*(?:"([^"\\]|\\.)+"|([^\s,=]+))\s*(?:,|$))+$/; return validationRegex.test(str); } // Test cases console.log(isValidKeyValueString('name=Alice, "full name"="Alice Smith", age=30')); // ✅ Valid console.log(isValidKeyValueString('name=Alice, full name=Alice Smith')); // ❌ Invalid (unquoted key with space) console.log(isValidKeyValueString('name=, age=30')); // ❌ Invalid (missing value for "name") console.log(isValidKeyValueString('"key with commas, here"="value with \\"escaped quotes\\""')); // ✅ Valid
2. Parsing into Key-Value Array
Instead of using split() (which would break on commas inside quoted values), we'll use a regex to match each valid key-value pair and extract the keys/values properly. This handles both quoted and unquoted entries, plus escaped quotes.
Here's the parsing function:
function parseKeyValueString(str) { if (!isValidKeyValueString(str)) { throw new Error('Input string does not follow valid key-value format'); } const pairRegex = /\s*(?:"([^"\\]|\\.)+"|([^\s,=]+))\s*=\s*(?:"([^"\\]|\\.)+"|([^\s,=]+))\s*/g; const keyValuePairs = []; let match; // Iterate through all matched pairs while ((match = pairRegex.exec(str)) !== null) { // Extract key: use quoted group (match[1]) if present, else unquoted (match[2]) const rawKey = match[1] || match[2]; // Extract value: same logic as key const rawValue = match[3] || match[4]; // Helper to unescape quotes (convert \" to ") const unescapeQuotes = (str) => str.replace(/\\"/g, '"'); keyValuePairs.push({ key: match[1] ? unescapeQuotes(rawKey) : rawKey, value: match[3] ? unescapeQuotes(rawValue) : rawValue }); } return keyValuePairs; } // Example usage const inputStr = 'name=Bob, "job title"="Senior Developer", "favorite food"="pizza, with extra cheese"'; const parsed = parseKeyValueString(inputStr); console.log(parsed); /* Output: [ { key: 'name', value: 'Bob' }, { key: 'job title', value: 'Senior Developer' }, { key: 'favorite food', value: 'pizza, with extra cheese' } ] */
Key Notes
- Quoted vs Unquoted: The regex ensures that any key/value containing spaces, commas, or equals signs must be wrapped in double quotes. Unquoted entries can only include alphanumeric characters and underscores (no spaces/special chars).
- Escaped Quotes: The regex handles escaped quotes (
\") inside quoted values, and the parsing function converts them back to regular quotes. - Why No
split()?: Usingsplit(',')would incorrectly split on commas inside quoted values. Matching pairs directly avoids this issue entirely.
内容的提问来源于stack exchange,提问作者vijay

