1

I'm converting a python script I wrote to javascript. My python script has the following regex to match single instances of '\':

re.sub(r'(?<!\\)(\\{1})(?!\\)', r'\\', word)

I got a compiler error when trying to run this in js:

"Invalid regular expression: /(?<!\\)(\\{1})(?!\\)/: Invalid group"

After some searching found out that regex in js does not support look behinds.

I looked at this answer and they used:

^(?!filename).+\.js

in the form of a negative look-ahead from the start of the string, which does not help me as I need to change '\' to '\\' anywhere in the string. I do not think this is a duplicate question as my question is trying to determine how to avoid and match the same character at different points in a string, while the linked question seeks to avoid a specific phrase from being matched.

I need to match '\' characters that do not have '\' either before or after them.

Community
  • 1
  • 1

2 Answers2

1

You always can use capture groups instead of lookbehind

string.match(/(^|[^\\])(\\{1})(?!\\)/)[2]

let replaced = "a\\b\\\\".replace(/(^|[^\\])(\\{1})(?!\\)/, x => x[0] == '\\' ? x : 'value')

console.log(replaced)

will return you same thing as (?<!\\)(\\{1})(?!\\)

Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32
0

Just match without assertions (^|[^\\])\\([^\\]|$) then substitute them back.
Note that this will tell you nothing about if it is escaping anything or not.
That regex is more complex.