Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for comma followed by space or just comma

is it possible to make a regex with multiple delimiters? For example I want to split a string which can come in two forms: 1. "string1, string2, string3" or 2. "string1,string2,string3". I've been trying to do this in javascript but with no success so far.

like image 556
DVM Avatar asked Sep 11 '12 11:09

DVM


3 Answers

Just use a regex split():

var string = "part1,part2, part3, part4,    part5",
    components = string.split(/,\s*/);

JS Fiddle demo.

The reason I've used * rather than ? is simply because it allows for no white-space or many white-spaces. Whereas the ? matches zero-or-one white-space (which is exactly what you asked, but even so).

Incidentally, if there might possibly be white-spaces preceding the comma, then it might be worth amending the split() regex to:

var string = "part1,part2  , part3, part4,    part5",
    components = string.split(/\s*,\s*/);
console.log(components);​

JS Fiddle demo.

Which splits the supplied string on zero-or-more whitespace followed by a comma followed by zero-or-more white-space. This may, of course, be entirely unnecessary.

References:

  • Regular Expressions.
  • string.split().
like image 112
David Thomas Avatar answered Oct 14 '22 20:10

David Thomas


Yes, make the whitespace (\s) optional using ?:

var s = "string1,string2,string3";
s.split(/,\s?/);
like image 31
João Silva Avatar answered Oct 14 '22 19:10

João Silva


In addition to silva

just in case you have doubt it can have more than one space then use (or no space)

var s = "string1, string2,  string3";
s.split(/,\s*/);
like image 32
dejjub-AIS Avatar answered Oct 14 '22 19:10

dejjub-AIS