You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript正则拆分键值对及格式验证技术问询

Solution for Parsing and Validating Key-Value Pairs in 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()?: Using split(',') would incorrectly split on commas inside quoted values. Matching pairs directly avoids this issue entirely.

内容的提问来源于stack exchange,提问作者vijay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:47:12