【问题标题】:JavaScript split by space ignoring parenthesesJavaScript 按空格分割,忽略括号
【发布时间】:2020-11-03 00:37:02
【问题描述】:

我正在尝试按空格分割字符串,但忽略括号中或左括号之后的字符串。我关注了this solution,但我的情况有点复杂。例如,如果括号是平衡的,则该解决方案可以正常工作:

// 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']

我应该如何做到这一点?

【问题讨论】:

  • 缺少的括号是否一致?您可以在拆分之前做一个预先步骤来添加括号吗?
  • 缺少的括号是真实情况。基本上用户会在前端的搜索框中输入这个字符串,它会随着输入的变化动态拆分这个字符串。
  • 能否在问题中包含拆分代码?

标签: javascript regex


【解决方案1】:

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

注意这样的情况

"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

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多