1

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.

Geuis
  • 41,122
  • 56
  • 157
  • 219
  • 1
    @anubhava ah I'll add that to the question. Doing this in javascript. – Geuis Aug 14 '18 at 18:46
  • Can backslash also be escaped like `a b/c\/d\\/e/f` ? – anubhava Aug 14 '18 at 18:59
  • Can't modify the source strings, really. – Geuis Aug 14 '18 at 19:02
  • Try using `(?:[a-z ])(\/)(?:[a-z ])` and then selecting group 1 on your code. Check this answer: https://stackoverflow.com/questions/18178597/non-capture-group-still-showing-in-match – João Miranda Aug 14 '18 at 19:08
  • 1
    Not asking to modify source input, I am asking if it is possible to get input as: `a b/c\/d\\/e/f` and with expected output as `['a b', 'c\/d\\', 'e' ,'f']` ? – anubhava Aug 14 '18 at 19:10

1 Answers1

1

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.
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • You say it will handle cases when ``\`` appears escaped, but [it does not work](https://regex101.com/r/RnKYza/3) for, say, ``\\\\\\/a b``. – Wiktor Stribiżew Aug 14 '18 at 21:06
  • `[^\\\/]*(?:\\.[^\\\/]*)*(?=\/|$)` can be used with `.filter(Boolean)` to get rid of empty matches – anubhava Aug 14 '18 at 21:12