Geuis
Geuis

Reputation: 42317

Trying to split string with escaped and non-escaped delimiter

I have a string with the form of a b/c\/d\/e/f. I'm trying to split the string on the non-escaped forward slashes.

I have this regex so far (?:[^\\/])/. However it consumes the last character preceding the /. So if I'm doing a replace with "#" instead of a split, the string looks like a #c\/d\/#f. In the case of the split, I get the strings separated the same with the last character being consumed.

I tried using a non capturing group but that doesn't seem to do the trick either. Doing this in javascript.

Upvotes: 1

Views: 142

Answers (1)

anubhava
anubhava

Reputation: 786359

You may use this regex in JS to return you all the matches before / ignoring all escaped cases i.e. \/. This regex also takes care of the cases when \ is also escaped as \\.

/[^\\\/]*(?:\\.[^\\\/]*)*(?=\/|$)/gm

RegEx Demo

const regex = /[^\\\/]*(?:\\.[^\\\/]*)*(?=\/|$)/gm
const str = `\\\\\\\\\\\\/a b/c\\/d\\\\/e\\\\\\/f1/2\\\\\\\\\\\\\\/23/99`;

let m = str.match(regex).filter(Boolean)

console.log(m)

  • .filter(Boolean) is used to filter out empty matches.

Upvotes: 1

Related Questions