Regular expression for a list of items separated by comma or by comma and a space

What you're looking for is deceptively easy:

[^,]+ 

This will give you every comma-separated token, and will exclude empty tokens (if the user enters "a,,b" you will only get 'a' and 'b'), BUT it will break if they enter "a, ,b".

If you want to strip the spaces from either side properly (and exclude whitespace only elements), then it gets a tiny bit more complicated:

[^,\s][^\,]*[^,\s]*

However, as has been mentioned in some of the comments, why do you need a regex where a simple split and trim will do the trick?


Assuming the words in your list may be letters from a to z and you allow, but do not require, a space after the comma separators, your reg exp would be [a-z]+(,\s*[a-z]+)*

This is match "ab" or "ab, de", but not "ab ,dc"


This thread is almost 7 years old and was last active 5 months ago, but I wanted to achieve the same results as OP and after reading this thread, came across a nifty solution that seems to work well

.match(/[^,\s?]+/g)

Here's an image with some example code of how I'm using it and how it's working

enter image description here

Regarding the regular expression... I suppose a more accurate statement would be to say "target anything that IS NOT a comma followed by any (optional) amount of white space" ?

Tags:

Regex