Regular expression to replace single backslashes, except those followed by specific characters

I have a regex expression that removes any backslashes from a string unless one of these characters is followed: \ / or}.

It should rotate this line:

foo\bar\\batz\/hi

In it:

foobar\\batz\/hi

But the problem is that it deals with every backslash when it goes. Thus, this rule follows that it removes this first backslash and ignores the second, because it is followed by another backslash. But when he gets to the third, he removes it, because the other does not follow him.

My current code is as follows: str.replace(/\\(?!\\|\/|\})/g,"")

But the resulting string looks like this: foobar\batz\/hi

3- ? , - ? . '\', '\\', '\/' '\}'?

, !:)

, - javascript, , lookbehinds...

+5
3

, . : . ( / {).

:

(?<!\\)(?:((\\\\)*)\\)(?![\\/{])

:

$1

- , .

:

(?<!\\)          # looking behind, there can't be a '\'
(?:((\\\\)*)\\)  # match an uneven number of backslashes and store the even number in group 1
(?![\\/{])       # looking ahead, there can't be a '\', '/' or '{'

ENG, :

, (?:((\\\\)*)\\), \\ { /, (?![\\/{]) (?<!\\).

Java (, !):

String s = "baz\\\\\\foo\\bar\\\\batz\\/hi";
System.out.println(s);
System.out.println(s.replaceAll("(?<!\\\\)(?:((\\\\\\\\)*)\\\\)(?![\\\\/{])", "$1"));

:

baz\\\foo\bar\\batz\/hi
baz\\foobar\\batz\/hi

, , :

([^\\])((\\\\)*)\\(?![\\/{])

:

$1$2

$1 - char , $2 - ( ) , char.

+5

, \\.

, replace() :

result = string.replace(/\\./g, function (ab) { // ab is the matched portion of the input string
    var b = ab.charAt(1);
    switch (b) { // if char after backslash
    case '\\': case '}': case '/': // ..is one of these
        return ab; // keep original string
    default: // else
        return b; // replace by second char
    }
});
+2

, , lookbehind, ( . :

(?<![\\])[\\](?![\\\/\}])

0
source

All Articles