简体   繁体   English

通过多个分隔符拆分字符串并保留一些分隔符而丢弃其他分隔符

[英]Split string by multiple delimiters and keeping some delimiters while discarding others

I would like to split by the space string " " while removing it and also split by a comma "," while keeping it.我想在删除它的同时用空格字符串" "分割","并在保留它的同时用逗号","分割。

var str = "This is a word, and another."
var regexKeepCommaDelimeter = new RegExp(/(,)/,'g')
var regexKeepCommaRemoveSpace = new RegExp(/(????)/,'g')
var splitArray = str.split(regexKeepCommaRemoveSpace)
var desiredArray = ['This', 'is', 'a', 'word', ',', 'and', 'another.' ]
var testPassed = splitArray.every((x,i)=> x == desiredArray[i])
console.log('Arrays match:', testPassed)

One fairly simple approach would be to add spaces around any , that don't have them, then just split on space:一种相当简单的方法是在 any 周围添加空格,没有它们,然后在空间上拆分:

var splitArray = str.replace(/ ?, ?/g, " , ").split(" ");

Live Example:现场示例:

 var str = "This is a word, and another." var splitArray = str.replace(/ ?, ?/g, " , ").split(" "); console.log(splitArray); var desiredArray = ['This', 'is', 'a', 'word', ',', 'and', 'another.' ]; console.log(splitArray.every((e, i) => e === desiredArray[i]));
 .as-console-wrapper { max-height: 100% !important; }

Match the space, and match and capture the comma when splitting with str.split(/\\s+|(,)/).filter(Boolean) .匹配空格,用str.split(/\\s+|(,)/).filter(Boolean)分割时匹配并捕获逗号。

Or, you may match any amount of chars other than whitespace and commas, or just a comma with str.match(/[^\\s,]+|,/g) .或者,您可以匹配除空格和逗号以外的任意数量的字符,或者只匹配一个带有str.match(/[^\\s,]+|,/g)的逗号。

 var str = "This is a word, and another."; console.log( str.split(/\\s+|(,)/).filter(Boolean) ); // => ["This", "is", "a", "word", ",", "and", "another."] console.log( str.match(/[^\\s,]+|,/g) ); // => ["This", "is", "a", "word", ",", "and", "another."]

The .filter(Boolean) part will remove empty items from the resulting array that appear due to eventual consecutive matches, or matches at the start of the string. .filter(Boolean)部分将从结果数组中删除由于最终连续匹配或匹配字符串开头而出现的空项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM