简体   繁体   中英

Split on javascript character with specific leading and trailing characters

I have a string which looks like this: "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']

You may match all the substrings you need with /(?:\\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:

  • \\s,\\S - a whitespace, , , non-whitespace
  • | - or
  • \\S,\\s - a non-whitespace, , , whitespace
  • | - or - [^,] - a char other than ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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