简体   繁体   English

用多个定界符分割字符串,并忽略引号中的定界符javascript

[英]Split a string by multiple delimiters and ignore delimiters in quotes javascript

I'm trying to write a regular expression to split a string into an array. 我正在尝试编写正则表达式以将字符串拆分为数组。 It must split using a delimiter of a space or comma, and ignore the delimiter inside of quoted phrases (using single or double quotes). 它必须使用空格或逗号的分隔符进行拆分,并忽略带引号的短语内部的分隔符(使用单引号或双引号)。

So far I'm able to get it to delimit by space and commas, but I'm unable to get it to ignore them between the quotation marks and I'm lost. 到目前为止,我可以通过空格和逗号来分隔它,但是我无法使它在引号之间忽略它们,我迷路了。

var pattern = /\b\w+[^"', ]+(?!'")/g,
    text = "Hello world \"Boston Red Sox\" hello, world, \'boston, red sox\', \'beached whale\', pickup sticks",
    output = text.match(pattern);

Current output: 电流输出:

["Hello", "world", "Boston", "Red", "Sox", "hello", "world", "boston", "red", "sox", "beached", "whale", "pickup", "sticks"] 

Desired output: 所需的输出:

["Hello", "world", "Boston Red Sox", "hello", "world", "boston, red sox", "beached whale", "pickup", "sticks"]

Any help would be great! 任何帮助将是巨大的!

Just use | 只需使用|

  var regex = /"([^"]*)"|'([^']*)'|[^\\s,]+/g; var text = "Hello world \\"Boston Red Sox\\" hello, world, \\'boston, red sox\\', \\'beached whale\\', pickup sticks"; var output = []; var m; while ((m = regex.exec(text)) !== null) { output.push(m[1] || m[2] || m[0]); } console.log(output); 

fiddle 小提琴

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

相关问题 用多个分隔符拆分字符串,保留它们并用双引号忽略它们 - Split string by multiple delimiters, keep them and ignore them in double quotes JavaScript字符串使用多个定界符进行拆分,同时保留定界符 - JavaScript String split with multiple delimiters while keeping the delimiters Javascript通过多个定界符将字符串拆分为逻辑表达式 - Javascript split string by multiple delimiters for logical expression 在 JavaScript 中组合多个分隔符(拆分) - Combining multiple delimiters (split) in JavaScript 根据多个分隔符 [/, #, @, ''] 拆分字符串 - Split a string based on multiple delimiters [/, #, @, ''] 根据多个分隔符拆分字符串 - Split a string based on multiple delimiters 用javascript中的多个定界符分割方程式字符串,并保留定界符,然后将字符串放回一起 - split equation string by multiple delimiters in javascript and keep delimiters then put string back together 通过 Javascript 中的成对分隔符拆分字符串,多次出现并排除 - Split string by paired delimiters in Javascript, on multiple occurrences, and with exclusions 通过多个分隔符拆分字符串并保留一些分隔符而丢弃其他分隔符 - Split string by multiple delimiters and keeping some delimiters while discarding others 根据开始和结束分隔符在javascript中拆分字符串 - split a string in javascript based on start and end delimiters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM