如何用空格分割字符串,并保持逗号分隔?

How is it possible to split a string by whitespaces, and also keep commas separate?

我想把一个句子分解成单词。如果它只包含空格,那么 .split(/\s+/) 有效。

但是怎么可能也用逗号分割,并且在结果数组中保留逗号呢?

我尝试过类似的方法,但它不起作用:

.split(/(?=,)|(?!=,)|\s/)

示例输入:

"this,is, a test"

预期输出:

["this", ",", "is", ",", "a", "test"]

我做错了什么?甚至可以只使用正则表达式吗?

你可以使用

console.log(
  "this,is, a test".match(/[^\s,]+|,/g)
)

参见regex demo

带有 g 修饰符的正则表达式的 String#match 方法提取所有非重叠的

  • [^\s,]+ - 除了空格 (\s) 和逗号
  • 之外的任何一个或多个字符
  • | - 或
  • , - 一个逗号。

如果您想按空格拆分并保留逗号,另一种选择可能是匹配 1 个以上的空格字符或捕获捕获组中的逗号以保留它并删除空条目。

(,)|\s+
  • (,) 在组 1 中捕获一个逗号以继续使用拆分
  • |
  • \s+ 匹配 1 个或多个空白字符

console.log(
  "this,is, a test"
  .split(/(,)|\s+/)
  .filter(Boolean)
);