2

我想将一个句子分成单词和单词之间的部分(我称之为分隔符)。

sentence = "First-tea,-then-coffee!"
=> "First-tea,-then-coffee!"
words = sentence.split(/\W+/) # Splits by non-word characters
=> ["First", "tea", "then", "coffee"]
delimiters = sentence.split(/\w+/) # Splits by word characters
=> ["", "-", ",-", "-", "!"]

拆分成单词效果很好,但我对分隔符有疑问。

第一个空字符串在分隔符数组中来自哪里?

感谢您的解释。

4

1 回答 1

0

在行/^/的开始和第一次-出现之间有"First"

所以它在"First"获得一个空字符串""-.

于 2012-07-19T08:58:24.650 回答