带有多个分隔符和Concat的分裂字符串

时间:2017-05-06 10:50:04

标签: javascript regex string algorithm split

我想从下面的这种字符串打印出所有可能的句子。最好的方法是什么?

[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend
  1. 我最好的朋友是
  2. 你最好的朋友
  3. 他最好的朋友是
  4. 她最好的朋友是
  5. 我真正的朋友
  6. 你真正的朋友
  7. 他真正的朋友
  8. 她真正的朋友是

  9. 谁是你最好的朋友

  10. 谁是她最好的朋友
  11. 谁是他最好的朋友
  12. 谁是你真正的朋友
  13. 谁是她真正的朋友
  14. 谁是他真正的朋友
  15. 哪里是你最好的朋友
  16. 她最好的朋友在哪里
  17. 哪里是他最好的朋友
  18. 你真正的朋友在哪里
  19. 她真正的朋友在哪里
  20. 他真正的朋友在哪里

1 个答案:

答案 0 :(得分:1)

没有内置功能可满足您的需求。所以你需要制定一个解决方案。

首先,您需要将此任务拆分为更重要的部分。

一部分会接受数组并在其上执行组合:

// Converts [['a'], ['b', 'c']] to ['ab', 'ac']
const combination = (parts) => {
  let current = [[]]
  parts.forEach(v => {
    let result = []
    current.forEach(c => {
      v.forEach(n => {
        result.push(c.concat(n))
      })
    })
    current = result
  })
  return current.map(v => v.join(' '))
}

另一部分需要将输入转换为数组数组并格式化输出:



const generate = (formats) => {
  let result = []

  // Converts [['a'], ['b', 'c']] to ['ab', 'ac']
  const combination = (parts) => {
    let current = [[]]
    parts.forEach(v => {
      let result = []
      current.forEach(c => {
        v.forEach(n => {
          result.push(c.concat(n))
        })
      })
      current = result
    })
    return current.map(v => v.join(' '))
  }
  formats.split('|').forEach((format) => {
    let parts = format
      .split(/[\]\[\)\(]/) // split "[a] (b) c" to ["a", "b", "c"]
      .filter(String) // remove empy elements
      .map(s => {return s.trim()})
      .filter(String) // there can be empty strings. remove those too
    parts = parts.map(part => {return part.split('/')})
    result = result.concat(combination(parts))
  })
  return result
}

let input = "[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend"
generate(input).forEach((v, i) => {console.log((i+1) + '. ' + v)})




这几乎是你需要的。虽然有一些角落案例应该被涵盖,但行.split(/[\]\[\)\(]/)有点问题。但我确定你可以解决它。

相关问题