繁体   English   中英

按空格分隔字符串,但忽略引号中的空格

[英]Split string by spaces but ignore spaces in quotation marks

我想用空格将一个字符串(任何字符串)分割成一个数组,最好使用split()方法。 但是,我希望忽略引号中的空格。

举个例子:

'word "words in double quotes"'

它应成为具有以下内容的数组:

[
  'word',
  'words in double quotes'
]

我看到了类似的答案,它们通常给出一个数组:

[
  'word',
  '"words in double quotes"'
]

那不是我想要的。 我不希望将引号添加到array元素中。

我可以使用什么正则表达式?

我认为单独使用String.prototype.split并不能实现您想要的结果,因为使用它很可能会导致结果数组中的字符串为空。 那就是你给的字符串。 如果您需要一个通用的解决方案,我相信split根本不会起作用。

如果您的目标是不管实际字符串如何都产生相同的结果,建议您使用String.prototype.match[].mapString.prototype.replace的组合,如下所示:

码:

 var /* The string. */ string = 'apples bananas "apples and bananas" pears "apples and bananas and pears"', /* The regular expression. */ regex = /"[^"]+"|[^\\s]+/g, /* Use 'map' and 'replace' to discard the surrounding quotation marks. */ result = string.match(regex).map(e => e.replace(/"(.+)"/, "$1")); console.log(result); 


正则表达式的解释:

  • "[^"]+" :捕获两个引号内除引号之外的任何字符序列(至少1个)
  • | :逻辑或。
  • [^\\s]+ :捕获任何非空格字符序列(至少1个)
  • g :全局标志-匹配所有出现的指令。

我希望这是您要寻找的:

 var words = 'word "words in double quotes" more text "stuff in quotes"'; var wordArray = words.match(/"([^"]+)"|[^" ]+/g); for(var i=0,l=wordArray.length; i<l; i++){ wordArray[i] = wordArray[i].replace(/^"|"$/g, ''); } console.log(wordArray); 

  1. 用“”分隔初始字符串
  2. 按空格将#1结果中的每个奇数项分开

使用正则表达式会极大地影响代码的可读性和可维护性。 尤其是当您尝试对现有限制(例如,缺乏后顾之忧)进行解决时。

暂无
暂无

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

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