V8 的正则 split 的实现?出现诡异的结果

理论上用正则对字符串进行 split 时,应是在匹配的每一个位置进行切割并扔掉匹配到的部分,然后以数组的形式返回

例如

',a,b,c,'.split(/,/) // return ['', 'a', 'b', 'c', '']
'abc'.split(/()/) // Expected to return ['', 'a', 'b', 'c', ''] as well

伪代码:

while (hasNextMatch()) {
  splitAt(matched().index)
  increaseLastIndex(matched().length || 1)
}

return calcResult()

完整实现:

function split(s, regex) {
  function implement() {
    while (hasNextMatch()) {
      splitAt(matched().index)
      increaseLastIndex(matched().length)
    }

    return calcResult()
  }

  function hasNextMatch() {
    return (lastMatch = regex.exec(s)) && (lastMatch = { index: lastMatch.index, length: lastMatch[0].length })
  }

  function matched() {
    return lastMatch
  }

  function increaseLastIndex(n) {
    regex.lastIndex += n || 1
    lastSplit += n
  }

  function splitAt(index) {
    result.push(s.substring(lastSplit, index))
    lastSplit = index
  }

  function calcResult() {
    result.push(s.substring(lastSplit, s.length))
    return result
  }

  var result = []
  var lastSplit = 0
  var lastMatch

  return implement()
}

console.log(split('abc', /()/g)) // [ '', 'a', 'b', 'c', '' ]

然而

'abc'.split(/()/g)

返回

['a', '', 'b', '', 'c']

图片描述

阅读 2.8k
1 个回答

'abc'.split(/(?:)/g)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题