简体   繁体   English

使用特定的前导和尾随字符拆分JavaScript字符

[英]Split on javascript character with specific leading and trailing characters

I have a string which looks like this: "foo, bar,baz" 我有一个看起来像这样的字符串: "foo, bar,baz"

I need your help with regexp to split it on commas that are surrounded by anything on both sides, eg ['foo, bar', 'baz'] 我需要您的正则表达式帮助,以将其拆分为两边都用逗号分隔的逗号,例如['foo, bar', 'baz']

You may match all the substrings you need with /(?:\\s,\\S|\\S,\\s|[^,])+/g regex: 您可以用/(?:\\s,\\S|\\S,\\s|[^,])+/g regex 匹配所有需要的子字符串:

 var regex = /(?:\\s,\\S|\\S,\\s|[^,])+/g; var str = "foo, bar,baz"; console.log(str.match(regex)); 

See the regex demo 正则表达式演示

The regex matches 1+ occurrences of: 正则表达式匹配1+次出现:

  • \\s,\\S - a whitespace, , , non-whitespace \\s,\\S -一个空白, , ,非空白
  • | - or - 要么
  • \\S,\\s - a non-whitespace, , , whitespace \\S,\\s -非空白, , ,空白
  • | - or - [^,] - a char other than , -或- [^,] -以外的其他字符,

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

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