JavaScript按空格分割字符串,忽略括号。

3

我想通过空格来拆分一个字符串,但要忽略括号内的空格和括号后面的空格。我参考了 这个解决方案,但我的情况稍微有点复杂。例如,如果括号是平衡的,那么该解决方案就能很好地工作:

// original string
let string = 'attribute1 in (a, b, c) attribute2 in (d, e)';
words = string.split(/(?!\(.*)\s(?![^(]*?\))/g);
console.log(words)

拆分后的预期结果:

words = ['attribute1', 'in', '(a, b, c)', 'attribute2', 'in', '(d, e)']

不过,如果括号没有平衡,举个例子:

// original string
let string = 'attribute1 in (a, b, c) attribute2 in (d, e';

我期望的结果应该是:

['attribute1', 'in', '(a, b, c)', 'attribute2', 'in', '(d, e']

替代

['attribute1', 'in', '(a, b, c)', 'attribute2', 'in', '(d,', 'e']

我该如何实现这个?


缺少的括号是否一致?您能否在分割之前执行预处理步骤以添加括号? - Adam Williamson
缺少括号是真正的问题。基本上,用户将在前端的搜索框中输入此字符串,并且随着输入的更改,它将动态地拆分此字符串。 - Alex Wang
你能否在问题本身中包含分割代码? - tadman
1个回答

3

我们可以通过在末尾添加缺失的括号来平衡字符串。

请注意,像以下情况:

"attribute1 in (a, b, c attribute2 in (d, e"

会导致以下结果:

[ 'attribute1', 'in', '(a,', 'b,', 'c', 'attribute2', 'in', '(d, e' ]

本解决方案假定这是预期的结果。

如果是,请使用以下解决方案:

/**
 * @param {string} s
 * @returns {string[]}
 */
function split(s) {
  let unclosed_count = 0;

  // count unclosed parentheses
  for (let i = 0; i < string.length; i++) {
    if (s[i] == '(') {
      unclosed_count++;
    } else if (s[i] == ')') {
      unclosed_count--;
    }
  }

  // close off the parentheses
  for (let i = 0; i < unclosed_count; i++) {
    s += ')';
  }

  // split
  let words = s.split(/(?!\(.*)\s(?![^(]*?\))/g);

  // remove the added parentheses from the last item
  let li = words.length - 1;
  words[li] = words[li].slice(0, -unclosed_count);

  return words;
}

let string = 'attribute1 in (a, b, c) attribute2 in (d, e';
let words = split(string);

console.log(words);
// => [ 'attribute1', 'in', '(a, b, c)', 'attribute2', 'in', '(d, e' ]

干杯!


还有一个值得考虑的情况是,不仅存在未匹配的开括号(,也存在一些未匹配的闭括号)

例如: "attribute1 in a, b, c) attribute2 in d, e)"

这个问题没有在题目中提到,因此也没有包含在解决方案中,但是如果这种情况很重要,那么你需要做与unclosed_count相反的事情,即使用unopened_count来解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接