-2

im new to regular expressions and i want to build an expression that finds the below pattern:

We have the string:

"'Hello world',dude, 'Somethings, never, turn and go', bye" 

I want a regular expression that gives this result:

['Hello world',dude,'Somethings, never, turn and go',bye]

Basically, splitting the string on comma but keeping the phrases with quotes that have comma as a whole.

I tried this ('\s*,\s*') but doesnt work.

Nick
  • 2,818
  • 5
  • 42
  • 60

2 Answers2

2

I think you want something like:

const regex = /(?:\'.*?\')|(?:\w+)/g;

const str = "'Hello world',dude, 'Somethings, never, turn and go', bye";

console.log(str.match(regex));
Alan Friedman
  • 1,582
  • 9
  • 7
1

Maybe try (?<=')\s*,\s*|\s*,\s*(?=')

let s = "'Hello world',dude, 'Somethings, never, turn and go', bye";
let arr = s.split(new RegExp(String.raw`(?<=')\s*,\s*|\s*,\s*(?=')`, 'g'));
console.log(arr)
JvdV
  • 70,606
  • 8
  • 39
  • 70
  • "dude, 'Somethings, never, turn and go'", are not splitted. Also the positive lookbehind may not be supported in all browsers – Nick Jul 08 '22 at 12:24
  • Yeah just noticed. Let me rework this. @Nick – JvdV Jul 08 '22 at 12:25
  • 1
    You can also use a literal in this case as you are not dynamically creating a regex `let arr = s.split(/(?<=')\s*,\s*|\s*,\s*(?=')/);` – The fourth bird Jul 08 '22 at 12:40
  • 1
    Right, even better! I'll leave my answer as is, and you keep the comment down to add value @Thefourthbird. – JvdV Jul 08 '22 at 12:47
  • the positive lookbehind may not be supported in all browsers – Nick Jul 08 '22 at 13:40
  • @JvdV if i add this string "'Hello world',dude, Somethings, never, turn and go, bye" it gives this result ["'Hello world'", 'dude, Somethings, never, turn and go, bye'] which is wrong. It doesnt split the other values separated by comma – Nick Jul 08 '22 at 23:05