【问题标题】:How to split a string using split(<regexp>) and get the separators? [duplicate]如何使用 split(<regexp>) 拆分字符串并获取分隔符? [复制]
【发布时间】:2018-06-13 17:26:51
【问题描述】:

我想使用 String.prototype.split(/[a-zA-Z]/) 在每个字母处拆分以下字符串:

'M 10 10L 150 300'

结果:

[ "", " 10 10", " 150 300" ]

但我想收到这个:

[ "", "M 10 10", "L 150 300" ]


使用 JavaScript 获得该结果的最快方法是什么?

【问题讨论】:

  • 这很接近:input.split(/(?=[A-Za-z])/)

标签: javascript arrays regex string split


【解决方案1】:

尝试使用匹配/[a-zA-Z][^a-zA-Z]*/g 来捕获一个字母和以下非字母字符:

let s = 'M 10 10L 150 300'

console.log(
  s.match(/^[^a-zA-Z]+|[a-zA-Z][^a-zA-Z]*/g)   // ^[^a-zA-Z]+ to include the case when 
                                               // the string doesn't begin with a letter
)

【讨论】:

  • 这缺少第一个空字符串条目。
  • @TimBiegeleisen 是的。不确定它有多重要。
  • @Psidom,不重要!!! :)
猜你喜欢
  • 2014-03-18
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2019-05-08
相关资源
最近更新 更多