2

I have a string: strString = first,last,,4443334444

I want to use regular expression to split this string into an array.

I'm using this regular expression [\""].+?[\""]|[^,]+ but it is ignoring the space after the word last.

So, my array is looking something like this:

        [0] => first
        [1] => last
        [2] => 4443334444 

instead of:

        [0] => first
        [1] => last
        [2] => 
        [3] => 4443334444

I would like to keep the space.

Any help would be appreciated.

dbc
  • 104,963
  • 20
  • 228
  • 340
The Goose
  • 21
  • 1
  • 3

3 Answers3

2

You may use

"[^"\\]*(?:\\.[^"\\]*)*"|[^,]+|(?<=^|,)(?=$|,)‌​

See the regex demo

The expression consists of

  • "[^"\\]*(?:\\.[^"\\]*)*" - a double quoted string literal with escape sequence support
  • | - or
  • [^,]+ - 1 or more characters other than ,
  • | - or
  • (?<=^|,)(?=$|,)‌​ - any empty string that is either between commas, or between the start/end of string and a comma.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

A couple of issues with your expression.

  1. First [\""] is redundant, use ["] or better " (without the character class) instead.
  2. Second, your actual problem is due to the + operator which requires at least one character (but there's none between the commas, thus disallowing empty fields).
  3. Third, this is probably some CSV output, so why not use explode() or similar functions?


If you insist on using a regular expression, you might get along with:
".*?"|[^,]*

See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79
0

Not sure if there's a way to get the element between the two commas, since there's no regex expression for it. The best I could come up with is:

str.match(/(?:[^,]+)|,,/g)

=> ["first", "last", ",,", "4443334444"]

But you'll need to translate the ",," into an empty string.

Is there a reason why you're using regex? Does your language have a .split() function? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Community
  • 1
  • 1
Louise
  • 151
  • 1
  • 8