kalkronline
kalkronline

Reputation: 743

Split Down Unescaped Character in Javascript

I have a period and backslash escaped string. I would like to split the string using any unescaped periods, but am struggling to come up with a pattern to do so.

const escaped = "two slashes: \\\\.one period: \..line and a dot: \\\.";

// ["two slashes: \\", "one period: .", "line and a dot: \."]
console.log(escaped.split(/* ? */))

This (?<!\\)(?:(\\\\)*)[*] is close, but split() includes capturing groups in the ouput array, which is not what I would like. The solution should be match-only, like here:

(?<!\\)(?:\\\\)*\K\.

Upvotes: 1

Views: 151

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

The positive lookbehind solution will work with any JavaScript environment compatible with ECMAScript 2018+ standard:

/(?<=(?<!\\)(?:\\\\)*)\./

See this regex demo.

enter image description here

The regex matches any . char that is immediately preceded with any amount of an even amount of backslashes (i.e. even if there are no backslashes before . at all).

With older JavaScript environment, you will need a workaround like text.match(/(?:\\[^]|[^\\.])+/g). See this regex demo. This matches any one or more sequences of a a \ and any single char or any single letter other than a backslash and a dot.

Upvotes: 1

Related Questions