0

Subsequent to Why this regex does split second double quote but not first double quote?

I now added :, problem is I don't want to split if it is inside double quotes:

let regex = /(?=\.|[\":])/;
test = "test: \"test.test:\""
test.split(regex)

gives

["test", ": ", ""test", ".test", ":", """]

whereas I would like to have

["test", ": ", ""test", ".test:", """]

is it possible for regex (I'm not good at all at it)?

user310291
  • 36,946
  • 82
  • 271
  • 487
  • You added the `:` without actually using the suggested solution? Again, note there is no sense separating `\.` and `[":]` patterns since both matcha single char, `(?=\.|[\":])` is the same as `(?=[.":])`. Actually, your desired result is equal to the current output. – Wiktor Stribiżew Apr 22 '20 at 18:59
  • 2
    Current output and expected outputs are exactly same. – anubhava Apr 22 '20 at 19:20
  • 1
    @anubhava because I made a bad copy and paste just fixed ;) – user310291 Apr 22 '20 at 19:42
  • @WiktorStribiżew I made a bad copy and paste. I used previous solution from anubhava because it was simpler to start with. I have yet to understand the other one. – user310291 Apr 22 '20 at 19:45

1 Answers1

2

You may use this regex to match : only outside quotes (assuming quotes are all balanced and unescaped):

const test = "test: \"test.test:\""
var arr = test.split(/(?=[."])|:(?=(?:(?:[^"]*"){2})*[^"]*$)/)

console.log( arr )

Here, (?=(?:(?:[^"]*"){2})*[^"]*$) is a lookahead that asserts that we have even number of quotes ahead of current position.

anubhava
  • 761,203
  • 64
  • 569
  • 643