简体   繁体   English

.split() 在空格和引号处,保留引号 - Regex/Javascript

[英].split() at spaces and quotation marks, keep quotation marks - Regex/Javascript

I would like to return an array from a string.我想从字符串返回一个数组。 The array should contain all characters as separate elements, except for spaces.该数组应包含所有字符作为单独的元素,但空格除外。 My current regex looks like this:我当前的正则表达式如下所示:

str = 'Stuff in "quotation marks"';
arr = str.split(/(?=["])|[\s+]/);
console.log(arr);
// [ 'Stuff', 'in', '"quotation', 'marks', '"' ]

I would like it to return something like this:我希望它返回这样的东西:

// [ 'Stuff', 'in', '"', 'quotation', 'marks', '"' ]

What regex can I use to return the " in front of '"quotation' as a separate element in the array?我可以使用什么正则表达式将“引用”前面的“作为数组中的单独元素返回?

You could use String.prototype.match() MDN你可以使用String.prototype.match() MDN

 const str = 'Stuff in "quotation marks"'; const arr = str.match(/\\w+|"/g); console.log(arr);

PS: Beware that \\w is analogous for [a-zA-Z0-9_] PS:注意\\w类似于[a-zA-Z0-9_]


You can also .split(/\\b/) at word boundaries /\\b/ but than trim and filter out empty values from the array:您还可以在字边界/\\b/处使用.split(/\\b/)但不是修剪和过滤掉数组中的空值:

 const str = 'Stuff in "quotation marks"'; const arr = str.split(/\\b/).map(w=>w.trim()).filter(w=>w); console.log(arr);

Disclaimer: the above examples will not work for special characters like š, ç, etc...免责声明:以上示例不适用于特殊字符,如 š、ç 等...

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

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